In C#, you can rename a file using the File.Move method from the
System.IO namespace. Here's how you do it:
Rename a File in C#
using System.IO;
string sourcePath = @"C:\path\to\oldFileName.txt";
string destinationPath = @"C:\path\to\newFileName.txt";
// This will rename the file (or move it if the path is different).
File.Move(sourcePath, destinationPath);
Notes:
This also moves the file if the destination path is in a different directory.
If destinationPath already exists, it will throw an IOException.
You can check if the file exists before renaming:
if (File.Exists(sourcePath) && !File.Exists(destinationPath))
{
File.Move(sourcePath, destinationPath);
}
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In C#, you can rename a file using the
File.Movemethod from theSystem.IOnamespace. Here's how you do it:Rename a File in C#
Notes:
This also moves the file if the destination path is in a different directory.
If
destinationPathalready exists, it will throw anIOException.You can check if the file exists before renaming: