Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have to copy some .txt files in to a different location.But the issue is i am unable to paste those files due to same name.I am getting those .txt files from different folder.I need to append a number to make .txt file unique and paste in to different location.My current code doesnt allow this.How can i do this?


What I have tried:

C#
foreach (var file in

      Directory.EnumerateFiles(extractPathForCurrentZip, "*.txt"))

                      {

 
                         File.Copy(file, DestinationFoldername+ Path.GetFileName(file));

}
Posted
Updated 18-Apr-22 21:42pm
Comments
Richard MacCutchan 19-Apr-22 3:35am    
You need to separate the filename and extension and modify the filename part to make it unique.

1 solution

The only way to do that is to fetch all the files, find the largest number at the end, add one to it, and then try to save that file - the sway that Windows does when you paste a file with the same name.
I'd add a separator to the file name - myFile.0000.txt, myFile.0001.txt, ... and so on to make it easier to separate the number part with a Regex.

I'd also suggest you use Path.Combine instead of concatenating strings (as it sorts out "\" separators for you) and use a try...catch block to detect overwrite attempts - remember that Windows can do several things at a time, so the "free number" you tried may not be free by the time you actually copy the file.
 
Share this answer
 
Comments
OriginalGriff 19-Apr-22 4:37am    
Because the file copy function will not let you overwrite the file - so if a copy existed last time, you still try to create it with the same name.

And your method is terrible: it generates files which aren't necessarily in sequence - you could generate 666_x.txt today, and 3_x.txt tomorrow depending on how many files it finds in the zip folder.

I'd put the number after the file name - so related files are easier to see together - and increment it (or better use a time stamp in the order yyyyMMddhhmmss) so that the latest version is at the end of each list.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900