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.

Download Code

 
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.

Download Code

 
We recommend putting validations around the File.Move() method to ensure that the path specified by sourceFilePath is valid.

Download Code

 
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().

Download Code

That’s all about moving a file in C#.