Sinilax
Sinilax

Reputation: 23

How can I rename files to a unique name that is fool proof in C#?

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

Answers (5)

John S
John S

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

David
David

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

Thomas Levesque
Thomas Levesque

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

Marcel
Marcel

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

Related Questions