2011-06-07 65 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 
相关问题