在我的vb.net winform应用程序中,我正在移动文件(例如:sample.xls从一个文件夹到另一个文件夹。如果文件已存在且名称相同,则应增加新文件名(例如:sample(1) ).xls)。我怎么能实现这个目标?
答案 0 :(得分: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
的import语句答案 1 :(得分: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