How to rename a file in c# or vb.net

To rename a file in c# or vb.net you need to Move it, there is no inbuild function that would just rename a file without moving.
The Move function can not overwrite a file and will throw a IOException if the file already exists, therefore we try to delete it first if it exists.

Sample C#

const string oldName = @"C:\OldFilename.txt";
const string newName = @"C:\NewFilename.txt";
File.Delete(newName); // First delete the new file if it exists, because it wont be overwritten by Move
File.Move(oldName, newName); // Move the file and give it a new name

Sample VB.NET

Const  oldName As String = "C:\OldFilename.txt"
Const  newName As String = "C:\NewFilename.txt"
File.Delete(newName) ' First delete the new file if it exists, because it wont be overwritten by Move
File.Move(oldName, newName) ' Move the file and give it a new name

Fore more informations see File.Move Method, File.Delete Method,IOException Class

Please Share us:
Please rate this snippet

2 thoughts on “How to rename a file in c# or vb.net

Leave a Reply