Move a file in C#
This post will discuss how to move a file in C#.
You can move files synchronously by using the File class from the System.IO namespace. The File.Move() method can be used to move the specified file to another location, using the same file name or a new one. The following code moves the file specified by sourceFilePath to the path specified by destinationFilePath using File.Move(). Note that the sourceFilePath and destinationFilePath can be either relative or absolute paths.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.IO; public class Program { public static void Main() { string sourceFilePath = @"C:\first.txt"; string destinationFilePath = @"C:\second.txt"; File.Move(sourceFilePath, destinationFilePath); } } |
The 2-arg File.Move() method throws a System.IO.IOException if you attempt to move a file when a file of the same name already exists in the destination. The File.Move() method is overloaded to accept an overwrite indicator which, if true, overwrites the destination file if it already exists.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.IO; public class Program { public static void Main() { string sourceFilePath = @"C:\first.txt"; string destinationFilePath = @"C:\second.txt"; File.Move(sourceFilePath, destinationFilePath, true); // overwrite - yes } } |
We recommend putting validations around the File.Move() method to ensure that the path specified by sourceFilePath is valid.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.IO; public class Program { public static void Main() { string sourceFilePath = @"C:\first.txt"; string destinationFilePath = @"C:\second.txt"; try { if (File.Exists(sourceFilePath)) { File.Move(sourceFilePath, destinationFilePath, true); } else { Console.WriteLine("Source file does not exist."); } } catch (Exception ex) { // handle other exceptions } } } |
You can also use the Directory.Move() method to move a file to a new location. The following sample moves the file pointed by sourceFilePath to the file pointed by destinationFilePath with Directory.Move().
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.IO; public class Program { public static void Main() { string sourceFilePath = @"C:\first.txt"; string destinationFilePath = @"C:\second.txt"; Directory.Move(sourceFilePath, destinationFilePath); } } |
That’s all about moving a file in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)