Dela via


Rename Function

Renames a disk file or directory.

The My feature gives you greater productivity and performance in file I/O operations than Rename. For more information, see My.Computer.FileSystem Object.

Public Sub Rename( _
   ByVal OldPath As String, _
   ByVal NewPath As String _
)

Parameters

  • OldPath
    Required. String expression that specifies the existing file name and location. OldPath may include the directory, and drive, of the file.

  • NewPath
    Required. String expression that specifies the new file name and location. NewPath may include directory and drive of the destination location. The file name specified by NewPath cannot already exist.

Exceptions

Exception type

Error number

Condition

ArgumentException

5

Path is invalid.

FileNotFoundException

53

OldPath file does not exist.

IOException

58

NewPath file already exists.

IOException

75

Access is invalid.

IOException

74

Cannot rename to different device.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You can compare the error number against the Number Property (Err Object).) However, when possible, you should consider replacing such error control with Structured Exception Handling Overview for Visual Basic.

Remarks

The Rename function renames a file and moves it to a different directory, if necessary. The Rename function can move a file across drives, but it can only rename an existing directory when both NewPath and OldPath are located on the same drive. Rename cannot create a new file or directory.

Using the Rename function on an open file produces an error. You must close an open file before renaming it. Rename arguments cannot include multiple-character (*) and single-character (?) wildcards.

Security noteSecurity Note:

When using Rename to copy a file from an unprotected location to a protected location, the file retains the less restricted rights. Check to make sure you are not introducing a possible security risk.

Example

This example uses the Rename function to rename a file. For purposes of this example, assume that the directories that are specified already exist.

Dim OldName, NewName As String
OldName = "OLDFILE" 
' Define file names.
NewName = "NEWFILE" 
' Rename file.
Rename(OldName, NewName)

OldName = "C:\OLDDIR\OLDFILE"
NewName = "C:\NEWDIR\NEWFILE" 
' Move and rename file.
Rename(OldName, NewName)

Smart Device Developer Notes

This function is not supported.

Requirements

Namespace:Microsoft.VisualBasic

**Module:**FileSystem

Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)

See Also

Tasks

How to: Rename a File in Visual Basic

How to: Rename a Directory in Visual Basic

Reference

Kill Function

ArgumentException

FileNotFoundException

IOException