ARTICLE AD BOX
I've been trying to figure this out for a while, but I can't seem to find a clear answer.
Is there a way to replace a file that already exists in a directory?
Context
I'm building an API that downloads CSV files from a website.
What I want is simple: if a .csv file already exists in the target directory, it should be replaced by the newly downloaded one — I do not want to end up with two .csv files fighting for dominance.
Here's the code that I've written so far:
string Extension = "*.csv"; string Path = AppContext.BaseDirectory; string DestinationDirectory = "lifters"; string fullDestinationPath = System.IO.Path.Combine(AppContext.BaseDirectory, DestinationDirectory); // Probleem nu is dat het een aparte file aanmaakt in de File Systems in plaats van dat hij gebruik maakt de gemaakte directory bool csvExists = Directory.EnumerateFiles(Path, Extension).Any(); try { if (!Directory.Exists(fullDestinationPath)) // Als het mapje niet eerder is gemaakt word er vanaf dit punt er een gemaakt waar de CSV files gestored worden { Directory.CreateDirectory(fullDestinationPath); } else if (csvExists) // Logica mocht de CSV bestand al bestaan { Console.WriteLine("CSV file is found!"); foreach (string file in Directory.EnumerateFiles(Path, Extension)) { string destinationPath = System.IO.Path.Combine(fullDestinationPath, System.IO.Path.GetFileName(file)); File.Move(file, destinationPath); } } }