How to Move a File in C#

Introduction 

 
The Move method moves an existing file to a new location with the same or a different file name.
 

How to move a File in C#?

 
The Move method takes two parameters. The Move method deletes the original file. A file Moves method a specified file to a new location, providing the option to specify a new file name.
 
File.Move renames a file. It is a tested .NET Framework method. The File class in the System.IO namespace provides this convenient method.
  • It performs a fast rename of the file you target.
  • It sometimes throws exceptions.

Move a File in C#

 
The Move method moves an existing file to a new location with the same or a different file name in File Move. The Move method takes two parameters. The Move method deletes the original file. The method that renames files is called File.Move.
 
We can include the System.IO namespace at the top with a using directive or specify the fully qualified name "System.IO.File.Move".
 
The following code snippet moves the source file to the destination file:
  1. {  
  2.     File.Move(sourceFile, destinationFile);  
  3. }  
  4. catch (IOException iox)  
  5. {  
  6.     Console.WriteLine(iox.Message);  
  7. }   
Example
  1. using System;  
  2. using System.IO;  
  3. class Test   
  4. {  
  5.     public static void Main()   
  6.     {  
  7.         string path = @"c:\temp\MySample.txt";  
  8.         string path2 = @"c:\temp2\MySample.txt";  
  9.         try   
  10.         {  
  11.             if (!File.Exists(path))   
  12.             {  
  13.                 // This statement ensures that the file is created,  
  14.                 // but the handle is not kept.  
  15.                 using (FileStream fs = File.Create(path)) {}  
  16.             }  
  17.             // Ensure that the target does not exist.  
  18.             if (File.Exists(path2))   
  19.             File.Delete(path2);  
  20.             // Move the file.  
  21.             File.Move(path, path2);  
  22.             Console.WriteLine("{0} was moved to {1}.", path, path2);  
  23.   
  24.             // See if the original exists now.  
  25.             if (File.Exists(path))   
  26.             {  
  27.                 Console.WriteLine("The original file still exists, which is unexpected.");  
  28.             }   
  29.             else   
  30.             {  
  31.                 Console.WriteLine("The original file no longer exists, which is expected.");  
  32.             }             
  33.         }   
  34.         catch (Exception e)   
  35.         {  
  36.             Console.WriteLine("The process failed: {0}", e.ToString());  
  37.         }  
  38.     }   
  39. }  

Summary

 
In this article, we learned about how to move a file in C#.