locked
CopyFile to same folder with unique filename RRS feed

  • Question

  • Hi

    I am using My.Computer.FileSystem.CopyFile() to make a copy of a file in the same folder.
    Currently I am determining a unique filename for the copy using my own code. However, is there a way to determine a unique filename in the same way that Explorer does it?

    For example, I copy the file c:\MyFile.txt
    and would like the first copy to be c:\Copy of MyFile.txt
    next copy is c:\Copy (2) of MyFile.txt
    then c:\Copy (3) of MyFile.txt
    etc.

    thanks

    Richard
    Tuesday, May 1, 2007 3:21 AM

Answers

  • The only win32 api call I am aware of that creates unique file names does not create them in that format.

     

    However, the code to do it is simple ....

     

    dim file as string = "Copy {0}{1}{2}Of MyFile.txt"

    dim s as string = "Copy Of MyFile.txt"

    dim n as integer = 1

    do while io.file.exists(s)

    s = string.format(file, "(", n.tostring, ") ") : n+=1

    loop

     

    The file name to use is contained in variable s.  Note that this is only safe if there is only one process generating the filename.  Wrap it with a monitor if you support concurrent file copying.

     

    Richard

    Tuesday, May 1, 2007 8:05 AM

All replies

  • The only win32 api call I am aware of that creates unique file names does not create them in that format.

     

    However, the code to do it is simple ....

     

    dim file as string = "Copy {0}{1}{2}Of MyFile.txt"

    dim s as string = "Copy Of MyFile.txt"

    dim n as integer = 1

    do while io.file.exists(s)

    s = string.format(file, "(", n.tostring, ") ") : n+=1

    loop

     

    The file name to use is contained in variable s.  Note that this is only safe if there is only one process generating the filename.  Wrap it with a monitor if you support concurrent file copying.

     

    Richard

    Tuesday, May 1, 2007 8:05 AM
  • thanks very much - that code is just what I've been looking for for a long time! Have put it to good use in a variety of places in my app .

    Only minor difference is that if you copy a file called "Copy (2) Of MyFile.txt", the new file will be named "Copy Of Copy (2) Of MyFile.txt" rather than "Copy (3) Of MyFile.txt". Not a big difference but may change this in future.

    thanks again

    Richard
    Thursday, May 3, 2007 2:53 AM