How to: Rename a File in Visual Basic
In Visual Basic, there are two ways to rename a file. You can use the Visual Basic run-time object My.Computer.FileSystem
or the .NET provided System.IO.File
object to rename a file.
Rename with .NET
The System.IO.File
object doesn't contain a method to rename a file, instead, use the Move
method to "move" the file to the same location but with a different file name. This method can also be used to move the file to a different location with a different name, performing a move and rename together.
The following example renames the file located in the My Documents
folder from TextFile.txt
to NewName.txt
.
Dim myDocsFolder As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim filePathSource = System.IO.Path.Combine(myDocsFolder, "TextFile.txt")
Dim filePathTarget = System.IO.Path.Combine(myDocsFolder, "NewName.txt")
System.IO.File.Move(filePathSource, filePathTarget)
Rename with the Visual Basic run-time
Use the RenameFile
method of the My.Computer.FileSystem
object to rename a file by supplying the full path to the file and the new file name. This method can't be used to move a file to a different directory. To learn how to move a file, see How to: Move a File in Visual Basic.
The following example renames the file located in the My Documents
folder from TextFile.txt
to NewName.txt
.
Dim myDocsFolder As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim filePath = System.IO.Path.Combine(myDocsFolder, "TextFile.txt")
My.Computer.FileSystem.RenameFile(filePath, "NewName.txt")
Visual Studio provides an IntelliSense code snippet that uses My.Computer.FileSystem.RenameFile
. The snippet is located in File system - Processing Drives, Folders, and Files. For more information, see Code Snippets.
Robust Programming
The following conditions might cause an exception:
- The path isn't valid for one of the following reasons: it's a zero-length string, it contains only white space, it contains invalid characters, or it's a device path (starts with \\.\) (ArgumentException).
newName
contains path information (ArgumentException).- The path isn't valid because it's
Nothing
(ArgumentNullException). newName
isNothing
or an empty string (ArgumentNullException).- The source file isn't valid or doesn't exist (FileNotFoundException).
- There's an existing file or directory with the name specified in
newName
(IOException). - The path exceeds the system-defined maximum length (PathTooLongException).
- A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
- The user lacks necessary permissions to view the path (SecurityException).
- The user doesn't have the required permission (UnauthorizedAccessException).