We can use File.Move or FileInfo.MoveTo methods to rename a file in C#. Here is a code snippet, where the first parameter is the full path of your current file and the second parameter is the name of the new file you want to rename your file to.
- System.IO.File.Move("FullPathOfAfile", "FullPathOfNewFile");
Here is the complete code of using FileInfo class. It does same as the above.
The following code snippet renames a source file into a new file by using the MoveTo method.
-
- string sourceFile = @"C:\Temp\MaheshChand.jpg";
-
- System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);
-
- if (fi.Exists)
- {
-
- fi.MoveTo(@"C:\Temp\Mahesh.jpg");
- Console.WriteLine("File Renamed.");
- }
Detailed tutorials: