Fraz Sundal Fraz Sundal -4 years ago 226
C# Question

How to Generate unique file names in C#

I have implemented an algorithm that will generate unique names for files that will save on hard drive. Im 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?

Answer Source

If readability doesn't matter, use GUIDs.

E.g.

var myUniqueFileName = string.Format(@"{0}.txt", Guid.NewGuid());

In my programs, I sometimes try e.g. 10 times to generate a readable name ("Image1.png".."Image10.png") and if that fails, 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);

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download