Link to home
Start Free TrialLog in
Avatar of jdana
jdanaFlag for United States of America

asked on

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.
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have used some variables which you would need to tweak but it gives you an idea.
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.
Avatar of jdana

ASKER

CodeCruiser,

You are the man.  Thank you!

J
Glad to help :-)