问题
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?
回答1:
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.
回答2:
File.Move should be a 'rename' if the source and destination are on the same volume. So, regardless of file size, the Move should be 'instant'. I presume that is your concern?
From a FAQ from a MS employee on http://msdn.microsoft.com/en-gb/library/windows/desktop/aa365240%28v=vs.85%29.aspx we have;
'Frequently asked question: Is MoveFileEx atomic if the existing and new files are both on the same drive?
The simple answer is "usually, but in some cases it will silently fall-back to a non-atomic method, so don't count on it".'
I guess if it's 100% critical you could look at Transactional NTFS. I'm not sure if there are wrappers in .Net for this yet, so you may need to use P/Invoke.
回答3:
This is a feature of windows, rather than c# or the .Net Framework.
See here
Atomicity of File.Move
回答4:
You can write your file directly to the destination and use a zero-size signal file that is created after you huge file is ready. Your reader process can look for a signal file and read a huge file after the signal file is available. I think that can solve the "atomicity" problem.
来源:https://stackoverflow.com/questions/15274861/file-move-atomic-operation