How to rename a file in VB.NET

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 is possible to rename a file and if the file exists, then rename it and add +1 to the file name?

So, if I run the code.

'Run it for the first time

My.Computer.FileSystem.RenameFile("c:\test\test.txt", "c:\test\NewName.txt")

'Run it again, but it should add +1 because the file already exists, so it should be "c: \ test \ NewName1.txt"

My.Computer.FileSystem.RenameFile("c:\test\test.txt", "c:\test\NewName.txt")

Update

I decided, but did not rename +1, it would be better to just stamp it, so for those who are struggling, like me:

My.Computer.FileSystem.RenameFile("c:\test\test.txt", "Test" & Format(Date.Now, "ddMMyy") & ".txt")
+5
source share
3 answers

You need to write your own logic for this.

The class Filehas many useful methods for working with files.

If File.Exists(filePath) Then
  ' Give a new name
Else
  ' Use existing name
End If

Path .

Path.GetFileNameWithoutExtension(filePath)
+8
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
+6

You do not need to specify the full path to the file in the parameter newFileName, just specify the 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
+2
source

All Articles