【问题标题】:How to increment the filename if file already exists如果文件已经存在,如何增加文件名
【发布时间】:2011-06-07 10:47:48
【问题描述】:

在我的 vb.net winform 应用程序中,我正在移动文件(例如:sample.xls 从一个文件夹到另一个文件夹。如果同名文件已经存在,则新文件名应递增(例如:sample(1 ).xls)。我怎样才能做到这一点?

【问题讨论】:

标签: .net vb.net


【解决方案1】:

上述过程在最后添加了计数器,但我的情况是想保留文件的扩展名,所以我将功能扩展为:

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

【讨论】:

    【解决方案2】:

    您好,这是一个非常“程序化”的答案:

    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 的导入语句

    【讨论】:

    • 如果有数百万个同名文件(例如图像序列),这不是一个好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 2015-12-09
    相关资源
    最近更新 更多