Error: The process cannot access the file

267 Views Asked by At

I use C# and try to merge some CSV files to one single CSV.

This works, but only once.

When I try it a second time I get

"The process cannot access the file "c:\test\CSV_merged.csv because it is being used by another process"

ProcessEplorer tells me that the file is in use by my application (CSV_Merge.exe)

However, I can delete "c:\test\CSV_merged.csv" using windows explorer (even though it is locked...?), and only then it works a second time

I've tried to use "using (StreamWriter....)" and in addition Flush(),Close(),Dispose() - even this should not be neccessary when I use "using (StreamWriter....)"?

Here is my code:

private void btnMergeCSVFiles_Click(object sender, EventArgs e)
{
    string sourceFolder = lblSelectedCSVFolder.Text;
    string destinationFile = lblSelectedCSVFolder.Text + "\\CSV_Files_Combined.csv";

    // Specify wildcard search to match CSV files that will be combined
    string[] CSVFiles = Directory.GetFiles(sourceFolder, "*.csv");

    using (StreamWriter fileDest = new StreamWriter(destinationFile))
    {
        //StreamWriter fileDest = new StreamWriter   (destinationFile, true);

        int i;
        for (i = 0; i < CSVFiles.Length; i++)
        {
            string file = CSVFiles[i];

            string[] lines = File.ReadAllLines(file);

            if (chkBoxCSVHasHeaderline.Checked && i > 0)
            {
                lines = lines.Skip(1).ToArray(); // Skip header row for all but first file
            }

            foreach (string line in lines)
            {
                fileDest.WriteLine(line);
            }
        }

        //fileDest.Flush();
        //fileDest.Close();
        //fileDest.Dispose();
    }

    //fileDest.Flush();
    //fileDest.Close();
    //fileDest.Dispose();
}

enter image description here

1

There are 1 best solutions below

0
Jonathan Joshua On

You should call File.ReadAllLines() outside of the using statement for StreamWriter. You are effectively trying to read from a file that is currently also being written.