2012-05-28 82 views
5

我瞭解如何在VB.NET中重命名文件,就像我在文章最後的代碼中使用的那樣。但是,我想知道是否可以重命名文件,如果文件存在,然後重命名文件名並添加+1文件名?如何在VB.NET中重命名文件

所以,如果我跑的代碼。

「運行它第一次

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

」再次運行它,但它應該添加+1如將已經存在的文件,因此它應該是‘C:\測試\ NewName1.txt’

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

更新

我決定,而不是重命名和+1,它會更好,只是日期戳它,所以任何人都像我一樣誰掙扎:

My.Computer.FileSystem.RenameFile("c:\test\test.txt", "Test" & Format(Date.Now, "ddMMyy") & ".txt") 

回答

8

您需要爲此編寫自己的邏輯。

File類有很多有用的方法來處理文件。

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

Path類有許多處理文件路徑的方法。

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

對不起,我不能添加編碼,所以請看第一篇文章。 – JackSparrow

2

您不必提newFileName參數完整的文件路徑,只是提到新的文件名,這裏否則你將得到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