2011-06-07 63 views
3

在我的vb.net WinForm應用程序,我移動文件(例如:sample.xls從一個文件夾到另一個文件是否已經具有相同名稱的存在,新的文件名應增加。(例如:樣品(1)的.xls)我怎樣才能達致這如何遞增的文件名,如果文件已經存在

+1

見http://stackoverflow.com/questions/1078003/c-how-would-you-make-a-unique-filename-by-adding -a-數爲這個問題的一個C#版本。 – stuartd 2011-06-07 10:49:33

回答

8

你好這裏是一個非常「程序」嗎?答案:

Dim counter As Integer = 0 

Dim newFileName As String = orginialFileName 

While File.Exists(newFileName) 
    counter = counter + 1 
    newFileName = String.Format("{0}({1}", orginialFileName, counter.ToString()) 
End While 

您將需要爲System.IO Imports語句

+0

若有數以百萬計的同名文件,例如圖像序列很好的解決方案。 – MrJD 2012-08-27 01:15:51

5

上述步驟添加計數器在最後,但我在我的情況下,想保持的進一步擴展該文件,所以我有功能擴展到這一點:

Public Shared Function FileExistIncrementer(ByVal OrginialFileName As String) As String 
    Dim counter As Integer = 0 
    Dim NewFileName As String = OrginialFileName 
    While File.Exists(NewFileName) 
     counter = counter + 1 
     NewFileName = String.Format("{0}\{1}-{2}{3}", Path.GetDirectoryName(OrginialFileName), Path.GetFileNameWithoutExtension(OrginialFileName), counter.ToString(), Path.GetExtension(OrginialFileName)) 
    End While 
    Return NewFileName 
End Function 
相關問題