Rename a file in C#

Take a look at System.IO.File.Move, "move" the file to a new name.

System.IO.File.Move("oldfilename", "newfilename");

System.IO.File.Move(oldNameFullPath, newNameFullPath);

In the File.Move method, this won't overwrite the file if it is already exists. And it will throw an exception.

So we need to check whether the file exists or not.

/* Delete the file if exists, else no exception thrown. */

File.Delete(newFileName); // Delete the existing file if exists
File.Move(oldFileName,newFileName); // Rename the oldFileName into newFileName

Or surround it with a try catch to avoid an exception.

Tags:

C#

File

Rename