Reputation: 23
My app needs to copy/move thousands of files throughout the day to a directory. I need to ensure that when I copy over these files I rename them to something that is unique for that directory.
I have no requirements for the names other than they need to obviously be unique.
What is the proper way to handle this? Should I use some kind of GUID, some incrementing number or some other method?
How would I do this in C#?
Upvotes: 2
Views: 1572
Reputation: 1
If you need the new file name to resemble the old one you could use this solution:
string oldFileName = @"c:\old\oldfile.txt";
string newFileName = oldFileName.Substring(0, oldFileName.LastIndexOf('.')) + "-";
string oldFileNameExtension = oldFileName.Substring( oldFileName.LastIndexOf('.')+1 );
File.Move(oldFileName, newFileName + DateTime.Now.Ticks.ToString() + oldFileNameExtension);
DateTime.Ticks is an integer of type Long which contains the current date converted to nanoseconds. Beware: most CPU's can perform many operations before the Ticks counter is advanced.
If you are doing many files at once you will have to add a while(File.Exists())
loop with a Thread.Sleep(10);
in it. Or if you don't want to slow it down with Thread.Sleep you could add a counter to the loop and append that to the end of newFileName.
Upvotes: 0
Reputation: 73564
I tend to use
System.Guid.NewGuid().ToString() + ".jpg"
when the only requirement is that they are absolutely required to be guaranteed to be unique.
This is, of course, already one of your ideas, so +1 to you for thinking of it first.
Upvotes: 6
Reputation: 292415
You can use Path.GetRandomFileName
However I don't think the generated filenames are guaranteed to be unique (they are generated using RNGCryptoServiceProvider), so a GUID might be a better idea
Upvotes: 11
Reputation: 15722
You can safely use GUID's. They are unique, and a filename can get generated with
String filename = Guid.NewGuid().ToString() + ".MyExtension";
br, Marcel
Upvotes: 0
Reputation: 10820
Use a GUID. Details are coming.
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5708732.html
Upvotes: 3