If possible this version uses the special File.Replace on NTFS and graciously falls back on Delete+Move on any other file system. Nothing else to comment about here. I am just amazed that this kind of save moving is not supported by the framework itself. Instead the framework's move routine throws an exception if there is an file existing at the target location. Weird. ;)

Just a heads up: Don't use this in performance critical parts...

C#:
  1. using System;
  2. using System.IO;
  3.  
  4. namespace Com.Hertkorn.Helper.Filesystem
  5. {
  6.   public static class FileMover
  7.   {
  8.     /// <summary>
  9.     /// Securely moves a file to a new location. Overwrites any
  10.     /// preexisting file at new location (= replacing file).
  11.     /// </summary>
  12.     /// <remarks>
  13.     /// If NTFS is available this is done via File.Replace.
  14.     /// If NTFS is not available it will be moved via deleting
  15.     /// any preexisting file and moving. Do NOT rely on the
  16.     /// backupFile being there - or not - after the move process.
  17.     /// That is not predetermined. This method is clearly
  18.     /// optimized for the case that NTFS is available. Consider NOT
  19.     /// using it on any other filesystem, if performance is an issue!
  20.     /// </remarks>
  21.     /// <param name="sourceLocation">The file to be
  22.     /// moved.</param>
  23.     /// <param name="targetLocation">The new resting
  24.     /// place of the file.</param>
  25.     /// <param name="backupLocation">A backup location that is
  26.     /// used when replacing on NTFS.</param>
  27.     public static void FileMove(
  28.         FileInfo sourceLocation,
  29.         FileInfo targetLocation,
  30.         FileInfo backupLocation)
  31.     {
  32.       if (targetLocation.Exists)
  33.       {
  34.         try
  35.         {
  36.           File.Replace(
  37.               sourceLocation.FullName,
  38.               targetLocation.FullName,
  39.               backupLocation.FullName, true);
  40.         }
  41.         catch (PlatformNotSupportedException)
  42.         {
  43.           // Not operating on an NTFS volume
  44.           if (targetLocation.Exists)
  45.           {
  46.             targetLocation.Delete();
  47.           }
  48.           File.Move(sourceLocation.FullName, targetLocation.FullName);
  49.         }
  50.       }
  51.       else
  52.       {
  53.         File.Move(sourceLocation.FullName, targetLocation.FullName);
  54.       }
  55.     }
  56.   }
  57. }

kick it on DotNetKicks.com