Wednesday, June 17, 2026

C# Rename one or more files of a folder

The FileInfo.MoveTo method is used to rename or move a filename.

Signatures
public void MoveTo(string destFileName);
public void MoveTo(string destFileName, bool overwrite);

  • Version1. Moves a specified file to a new location, providing the option to specify a new file name.
  • Version2. Moves a specified file to a new location, providing the options to specify a new file name and to overwrite the destination file if it already exists.

Example1. Rename a file

Syntax: FileInfo.MoveTo(String "new FileName with full path") to rename.

string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string source_folder = Path.Combine(desktop, "source_folder");

if (Directory.Exists(source_folder))
{
    FileInfo fileInfo = new FileInfo(Path.Combine(source_folder, "abc.txt"));

    fileInfo.MoveTo(Path.Combine(source_folder, "xyz.txt"));
    Console.WriteLine("File is renamed successfully.");
}
else
{
    Console.WriteLine("File was not renamed or found.");
}
NOTE: What if xyz.txt file already exists? You get exception: System.IO.IOException: 'Cannot create a file when that file already exists.' To overwrite the existing xyz.txt, use version2 style code:
fileInfo.MoveTo(Path.Combine(source_folder, "xyz.txt"), true);

Example2. Rename files of a folder by prefixing with text
static void Main()
{
    string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    string source_folder = Path.Combine(desktop, "source_folder");

    if (Directory.Exists(source_folder))
    {
        string[] files = Directory.GetFiles(source_folder);

        foreach (string file in files)
        {
            FileInfo fileInfo = new FileInfo(file);

            string newPath =
                Path.Combine(source_folder, "new_" + fileInfo.Name);

            fileInfo.MoveTo(newPath);
        }
        Console.WriteLine("Files renamed successfully.");
    }
    else
    {
        Console.WriteLine("Source folder not found.");
    }
}

No comments:

Post a Comment

Hot Topics