I have implemented an algorithm that will generate unique names for files that will save on hard drive. I'm appending DateTime
: Hours,Minutes,Second and Milliseconds but still it generates duplicate name of files because im uploading multiple files at a time.
What is the best solution to generate unique names for files to be stored on hard drive so no 2 files are same?
If readability doesn't matter, use GUIDs.
E.g.:
var myUniqueFileName = string.Format(@"{0}.txt", Guid.NewGuid());
or shorter:
var myUniqueFileName = $@"{Guid.NewGuid()}.txt";
In my programs, I sometimes try e.g. 10 times to generate a readable name ("Image1.png"…"Image10.png") and if that fails (because the file already exists), I fall back to GUIDs.
Update:
Recently, I've also use DateTime.Now.Ticks
instead of GUIDs:
var myUniqueFileName = string.Format(@"{0}.txt", DateTime.Now.Ticks);
or
var myUniqueFileName = $@"{DateTime.Now.Ticks}.txt";
The benefit to me is that this generates a shorter and "nicer looking" filename, compared to GUIDs.
Please note that in some cases (e.g. when generating a lot of random names in a very short time), this might make non-unique values.
Stick to GUIDs if you want to make really sure that the file names are unique, even when transfering them to other computers.
Use
Path.GetTempFileName()
or use new GUID().
Path.GetTempFilename() on MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With