This post will discuss how to rename a file using C#.

1. Using File.Move() method

The File.Move() method is used to move a specified file to a new location. The following example demonstrates how to use the File.Move() method for renaming a file. If the file is renamed successfully, a success message is displayed. If the source file doesn’t exist or the destination file is already present, an IOException would be thrown.

Download Code

 
File.Move throws an IOException when the destination file already exists. We can handle this in two ways:

 
1. Call the Move overload by setting the overwrite parameter to true, overwriting the destination file if it exists.

Download Code

 
2. Call the Delete() method before calling the Move() method, which will delete the destination file if it exists.

Download Code

 
If the source and destination directory are the same, this will delete the source file before moving. This is handled below:

Download Code

2. Using File.Copy() method

Another approach to renaming a file involves using the File.Copy() method. Here, the idea is to copy the source file to the destination file and then delete the source file. This approach is demonstrated below and should be used only with small files.

Download Code

That’s all about renaming a file with C#.