File.Move atomic operation

Murtaza Mandvi picture Murtaza Mandvi · Mar 7, 2013 · Viewed 7.8k times · Source

I am trying to generate a huge text file using C# and another process is constantly looking at the location and trying to pickup the file if available.

In order to make the file atomic below are the steps :

1 - Write to file : Filename_temp.txt
2 - Check if Filename.txt already exists then Delete
3 - Do a File.Move to the same destination     
    From filename : Filename_temp.txt 
    TO : Filename.txt

Since C# does not have a rename, I have to rely on File.Move, does this make sure the move operation will be atomic or is there another way to achieve this atomicity?

Answer

Heinzi picture Heinzi · Mar 7, 2013

According to the MSDN blog article How to do atomic writes in a file, renaming an NTFS file is an atomic operation:

The solution? Let's remember that metadata changes are atomic. Rename is such a case. So, we can just perform the write to a temporary file, and after we know that the writes are on the disk (completed and flushed) then we can interchange the old file with the new file.

Granted, this does not guarantee that File.Move just issues an NTFS rename operation, but I can't think of a valid reason why it should do anything more complicated.