• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 200
  • Last Modified:

Trying to deal with duplicate file names

Can someone help me out with a fix for this?  I've built a recursive method that copies all Word documents from a parent directory and all child directories of the parent, and pastes them into a single flat directory.  The method works fine as long as a Word document file name isn't repeated.  If it is, however, the method bonks.  I'd like to append a "(2)", "(3)", "(4)" onto the second, third, and forth versions of the document (myDocument(2).docx, myDocument(3).docx, myDocument(4).docx...) .  Here are the couple lines of code that copy each Word document.

fullPath = The full path of the file being copied.
FlatFolder = The target directory.

string fileNameOnly = Path.GetFileName(fullPath);
File.Copy(fullPath, FlatFolder + @"\" + fileNameOnly);

Open in new window


Iv'e thought about letting the error occur, trapping the error, and responding accordingly.  I've also assigning each file name as an array element and then inspecting the array with each new file.
0
jdana
Asked:
jdana
  • 3
1 Solution
 
CodeCruiserCommented:
I use following


Dim FileToCopy As String = FolderPath & DestinationFileName & IO.Path.GetExtension(SourceFileName)
            Dim ext As String
            If IO.File.Exists(FileToCopy) Then
                Dim inc As Int16 = 1
                ext = IO.Path.GetExtension(SourceFileName)
                While IO.File.Exists(FolderPath & DestinationFileName & " (" & inc & ")" & ext)
                    inc += 1
                End While
                FileToCopy = FolderPath & DestinationFileName & " (" & inc & ")" & ext
            Else
                FileToCopy = FolderPath & DestinationFileName & IO.Path.GetExtension(SourceFileName)
            End If

Open in new window

0
 
CodeCruiserCommented:
I have used some variables which you would need to tweak but it gives you an idea.
0
 
anarki_jimbelCommented:
I believe the solution above is good one.

"Iv'e thought about letting the error occur, trapping the error, and responding accordingly.  I've also assigning each file name as an array element and then inspecting the array with each new file."
I wouldn't do that. Check if this name exist as CodeCruised does. Using exceptions for program flow is not  a proper way I think.
0
 
jdanaAuthor Commented:
CodeCruiser,

You are the man.  Thank you!

J
0
 
CodeCruiserCommented:
Glad to help :-)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now