在我的vb.net winform应用程序中,我正在移动文件(例如:sample.xls从一个文件夹到另一个文件夹.如果文件已经存在同名,则新文件名应该递增(例如:sample(1).xls ).我怎么能实现这一点?
嗨,这是一个非常"程序化"的答案:
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
Run Code Online (Sandbox Code Playgroud)
您将需要System.IO的import语句
上面的过程在最后添加了计数器,但我的情况是想保留文件的扩展名,所以我将函数扩展为:
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11052 次 |
最近记录: |