You can use the RenameFile method of the My.Computer.FileSystem object to rename a file by providing source file name with full path and the new file name.
You can use this method as:
My.Computer.FileSystem.RenameFile(file,newName)
file : File to be renamed. this is required parameter.
newName : New name of file. this is also required parameter.
Example
This example renames the file hello.txt to helloWorld.txt which is located in C:\myFiles
directory.
My.Computer.FileSystem.RenameFile("C:\myFiles\hello.txt", "helloWorld.txt")
There are many possible exception of the above code such as if code doesn’t find the file with the specified name or code does not have PathDiscovery permission, code will throw FileNotFoundException
exception, similarly if current user has not necessary permissions to view the path, code will throw SecurityException
.
SecurityException
and if user does not have the required permission UnauthorizedAccessException
will be thrown.The file path should not be excess than system defined max length so generally program doesn’t support the file path excess than 260 characters, specially if your program is running prior to the .NET Framework 4.6.2, the file path should not be greater than 260 characters. In this situation code will throw PathTooLongException
exception.
Rename folder
Similarly you can change the folder name using My.Computer.FileSystem
.
You can use the below method:
My.Computer.FileSystem.RenameFile(directory,newDirectryName)
And you can write your code as:
My.Computer.FileSystem.RenameDirectory("C:MyDocuments\Test", "SecondTest")
Mostly all above exceptions will also applied here.