Atomic file-sustitution in .NET?

  • Thread starter Thread starter Helge Jensen
  • Start date Start date
H

Helge Jensen

On unix-based systems i use (the libc function) "rename" to do atomic
replacement of one file with another.

How would I achieve the same using .NET primitives?
 
Helge said:
On unix-based systems i use (the libc function) "rename" to do atomic
replacement of one file with another.

How would I achieve the same using .NET primitives?

There are two Windows API functions that might be useful: ReplaceFile and
MoveFileEx. Both seem to be able to replace a file if used with the
correct parameters, but none of them guarantee atomicity. I don't think
any of them is available via .NET framework classes.

I googled for "windows posix rename" and I came up with a few mailing list
threads discussing the issue, with the general consent being that Windows
can't do it - many things in Windows file handling aren't very POSIX
compatible, after all.


Oliver Sturm
 
Oliver said:
I googled for "windows posix rename" and I came up with a few mailing
list threads discussing the issue, with the general consent being that
Windows can't do it - many things in Windows file handling aren't very

Unfortunatly , this is what I suspected :(
POSIX compatible, after all.

I'm not really too interested in whether the behaviour is POSIX, but in
mechanisms to guarantee consistency during updates. I guess ill have to
live with the race-condition and data-loss possibility of the pattern:

if ( File.Exists(path) )
File.Remove(path);
File.Move(path, newpath);
 
Helge said:
I'm not really too interested in whether the behaviour is POSIX, but in
mechanisms to guarantee consistency during updates. I guess ill have to
live with the race-condition and data-loss possibility of the pattern:

if ( File.Exists(path) )
File.Remove(path);
File.Move(path, newpath);

There's no way around that pattern, I think. But it should read:

if ( File.Exists(newpath) )
File.Remove(newpath);
File.Move(path, newpath);


Oliver Sturm
 
There's no way around that pattern, I think. But it should read:

if ( File.Exists(newpath) )
File.Remove(newpath);
File.Move(path, newpath);

Thanks, for pointing out my typo ;)
 
Back
Top