Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Generate unique file names in C#

Tags:

c#

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?

like image 459
Fraz Sundal Avatar asked Jan 11 '11 13:01

Fraz Sundal


2 Answers

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.

like image 120
Uwe Keim Avatar answered Nov 16 '22 20:11

Uwe Keim


Use

Path.GetTempFileName()

or use new GUID().

Path.GetTempFilename() on MSDN.

like image 94
KBBWrite Avatar answered Nov 16 '22 19:11

KBBWrite