c# - without - unable to remove the file to be replaced




Difference between File.Replace and(File.Delete+File.Move) in C# (3)

Today I ran into a strange problem: Since a year and several versions / tests of the application the following code has been used successfully to replace a file with an other.

File.Replace(path + ".tmp", path, null);

This has worked locally and also with UNC paths (network shares). But today I got the following error when I used this code to replace a file on a UNC path (local still works):

The process cannot access the file because it is being used by another process

When I use the following code instead of the above, it works:

File.Delete(path);
File.Move(path + ".tmp", path);

So my questions:

  • What is the difference between the two code snippets?
  • Could it be that Microsoft have changed the way 'File.Replace' works?

I'm using .Net Framework 4.0 with Visual Studio 2010.

Thanks in advance.


According to MSDN on File.Replace

File.Replace will throw an exception when...

  • the destination file is missing.
  • source and destination are on different volumes

Which File.Delete, File.Move won't.


Here's the MSDN article on File.Replace()

Creating a backup of the original appears to be the difference.


using System;
using System.IO;

namespace FileSystemExample
{

class FileExample
{

    public static void Main()
    {
        try
        {

            string OriginalFile = path+"test.tmp";
            string FileToReplace = path+"test2.tmp";
            string BackUpOfFileToReplace = path+"test2.tmp.bac";


            Console.WriteLine("Move the contents of " + OriginalFile + " into " + FileToReplace + ", delete " + OriginalFile +
                               ", and create a backup of " + FileToReplace + ".");

            // Replace the file.
            ReplaceFile(@OriginalFile, @FileToReplace, @BackUpOfFileToReplace);

            Console.WriteLine("Done");
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        Console.ReadLine();
    }

    // Move a file into another file, delete the original, and create a backup of the replaced file.
    public static void ReplaceFile(string FileToMoveAndDelete, string FileToReplace, string BackupOfFileToReplace)
    {
        File.Replace(FileToMoveAndDelete, FileToReplace, BackupOfFileToReplace, false);

    }
}

}





.net