tags:

views:

118

answers:

2

I'm trying to use System.IO.File.Replace to update a file, and it's throwing System.IOException if the destination file is on a NAS.

According to MSDN, if the destination file is on a different volume, this method throws an exception. It's right, but how do I detect if two files are on "different volumes"?

Path.GetPathRoot returns different strings if I specify the same file using drive letters, mapped drives, or UNC paths. I can't catch System.IOException because that is thrown in a variety of cases, not just if the files are on different volumes.

A: 

If you have a chance that the files will be on separate volumes, it's best to write your own simple copy routine that reads from one stream and writes out to the other. This handles cross-volume copies, allows you to catch the other exceptions you might hit and is pretty simple to implement.

ctacke
Alas, experience has shown me that this is not simple to implement. File.Replace handles locking and atomic renaming of files, backup for errors, file attributes, user permissions, NTFS forks, Windows Explorer Summary comments, ... avoid doing it yourself if at all possible.
Dour High Arch
+1  A: 

You could ensure the replace is always on the same volume by using Copy, then Replace. Or just catch the error and try it.

catch IOException
  File.Copy( src,dest+".tmp", true )
 File.Replace( dest+".tmp", dest, dest_backup )
Sanjaya R