开发者

How to increment the filename if file already exists

In my vb.net winform application, I am moving the file (ex: sample.xls 开发者_开发知识库from one folder to another. If file already exists with the same name, the new file name should be incremented (ex:sample(1).xls). How can i acheive this?


Hi here's a pretty "procedural" answer:

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

you will need an imports statement for System.IO


The above procedure add the counter at the end, but i my case a want to keep the extention of the file, so i have expanded the function to this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜