I keep getting the following exception:
System.IO.IOException HResult=0x80070020 Message=The process cannot access the file 'C:\DIPV3\result.csv' because it is being used by another process.
Is there a better way to attempt this solution using a combination of Streams or Linq? The code below writes the file partially but then throws an the exception stated above.
string sourceDir = @"C:\DIPV3"; string output = @"C:\DIPV3\result.csv"; //Thread.Sleep(5000); File.WriteAllLines(output, Directory.EnumerateFiles(sourceDir, @"*.csv").SelectMany(file => File.ReadLines(file)));
The problem is that you're trying to write to the same file that you're reading from (your
output file is in the sourceDir and matches the
A few possible solutions are:
1 . Select all files except the output file for reading:
File.WriteAllLines(output, Directory.EnumerateFiles(sourceDir, @"*.csv") .Where(path => !path.Equals(output, StringComparison.OrdinalIgnoreCase)) .SelectMany(File.ReadLines));
2 . Put your output file in a different folder:
string output = @"C:\DIPV3\restuls\result.csv";
3 . Read all the contents first, then write the result:
IEnumerable<string> contents = Directory.EnumerateFiles(sourceDir, @"*.csv") .SelectMany(File.ReadLines).ToList(); File.WriteAllLines(output, contents);
User contributions licensed under CC BY-SA 3.0