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.


Just add:

namespace System.IO
{
    public static class FileInfoExtensions
    {
        public static void Rename(this FileInfo fileInfo, string newName)
        {
            fileInfo.MoveTo(Path.Combine(fileInfo.Directory.FullName, newName));
        }
    }
}

And then...

FileInfo file = new FileInfo("c:\test.txt");
file.Rename("test2.txt");

You can use File.Move to do it.