Austin
Austin

Reputation: 3080

Can't get overwrite to work during File.Copy - unable to access error

I have been looking all at kinds of solutions for allowing an overwrite to occur from the following error

{"The process cannot access the file 'C:\pathway\filename.txt' because it is being used by another process."}

I have tried, flushing, closing, GC.Collect(), ect... but I cannot seem to find a way pass this error.

I write a "temp" file as such

        using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                foreach (var line in detailLines)
                {
                    sw.WriteLine(line);
                }
                sw.Flush();
                sw.Close();
            }
        }
        GC.Collect();

Then allow the user to specify their own destination where I copy the file above, to.

private void SaveFile()
{
    SaveFileDialog saveFile = new SaveFileDialog();
    saveFile.FileName = fileName;
    saveFile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";            
    if (saveFile.ShowDialog() == DialogResult.OK)
    {
        System.IO.File.Copy(fileName, saveFile.FileName, true);
    }
}

I can save as a new name fine, but if I attempt to save at the same pathway and name as the "temp" file, then it asks "if I want to replace this file" and after I click yes it crashes and throws that cannot access error.

Can someone explain how I can access and overwrite a file in the same destination?

Upvotes: 0

Views: 1107

Answers (1)

Eugene Podskal
Eugene Podskal

Reputation: 10401

Despite the fact that File.Copy method says that:

Overwriting a file of the same name is allowed.

It actually fails to succeed in it(looks like something else has been meant by this sentence):

try
{
    String filePath = @"C:\TEMP\test.txt";
    using (var fs = new StreamWriter(filePath))
    {
        fs.Write("data");
    }

    Console.WriteLine("File written");

    // Fails
    System.IO.File.Copy(filePath, filePath, true);

    Console.WriteLine("File overwritten by itself");

}
catch (Exception exc)
{
    Console.WriteLine(exc.Message);
}

So, you should probably just check whether the temp file and target file are the same and act accordingly:

if (fileName != saveFile.FileName)
    System.IO.File.Copy(fileName, saveFile.FileName, true);

P.S.: There is always some probability of race conditions in the file system, but I don't think that you should really worry about it - dealing with it will just make your code more complex and improve nothing.

Upvotes: 2

Related Questions