How to fix System.IO Exception in C#. Attempting to collate multiple CSV files into 1 file

-1

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)));
c#
linq
file-io
asked on Stack Overflow Apr 30, 2019 by Denz • edited Apr 30, 2019 by Rufus L

1 Answer

2

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 "*.csv" filter.

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);
answered on Stack Overflow Apr 30, 2019 by Rufus L • edited Apr 30, 2019 by (unknown user)

User contributions licensed under CC BY-SA 3.0