Uredi

Deli z drugimi prek


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:

See also