Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment the filename if file already exists

Tags:

.net

vb.net

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?

like image 912
Ram Avatar asked Jun 07 '11 10:06

Ram


People also ask

How to increment the filename if file already exists in java?

Calling getUniqueFileName(new File('/dir/example. txt') when 'example. txt' already exists while generate a new File targeting '/dir/example (1). txt' if that too exists it'll just keep incrementing number between the parentheses until a unique file is found, if an error happens, it'll just give the original file name.

What happens if file already exists Java?

If the file name doesn't yet exist, it will work fine. But if the file name already exists, then the user will get the "nameAlreadyExists()" alert dialog but the file will still be added and overwritten.

Does filename include extension?

A filename may (depending on the file system) include: name – base name of the file. extension (format or extension) – indicates the content of the file (e.g. . txt , .exe , .


1 Answers

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

like image 191
Rendition Avatar answered Oct 05 '22 13:10

Rendition