I understand how to rename a file in VB.NET as I use in the code at the end of my post. However, I was wondering if it\'s possible to rename a file and if the file exists th
Public Sub RenameFile(ByRef FileFind As String, ByRef NewReplaceFileName As String)
Dim Ada As String = Path.GetFileNameWithoutExtension(FileFind)
'VS2013 Dim Ada As String = File.Exists(FileFind)
If Ada.Length > 0 Then
My.Computer.FileSystem.RenameFile(FileFind, NewReplaceFileName)
Exit Sub
Else
MsgBox("File doesn't exists")
End If
End Sub
You don't need to mention the complete file path in newFileName
parameter, just mention new file name here otherwise you will get ArgumentException
.
Dim filePath As String = "C:\fingerprint1"
If File.Exists(filePath) Then
Dim strNewFileName As String = "Fingerprint221"
My.Computer.FileSystem.RenameFile(filePath, strNewFileName)
End If
Another simple way to rename a file is to use the Move() method of System.IO.File.
Example:
System.IO.File.Move("C:\temp\file1.txt", "C:\temp\file1_renamed.txt")
You need to write your own logic for this.
The File class has many useful method for dealing with files.
If File.Exists(filePath) Then
' Give a new name
Else
' Use existing name
End If
The Path class has many methods for dealing with file paths.
Path.GetFileNameWithoutExtension(filePath)
If System.IO.File.Exists("c:\test\NewName.txt") Then
' add +1 or loop exists with increment on the end until file doesn't exist
End If