Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a random image name in C#?

When I add a picture I want it to create a new random file name because if you add a picture with the same name it will just overwrite.

like image 623
saadan Avatar asked May 12 '10 08:05

saadan


3 Answers

The is a built-in method Path.GetRandomFileName. It returns a random folder name or file name.

The GetRandomFileName method returns a cryptographically strong, random string that can be used as either a folder name or a file name. Unlike GetTempFileName, GetRandomFileName does not create a file. When the security of your file system is paramount, this method should be used instead of GetTempFileName.

If you want to use your extension (e.g. .jpg instead of generated), you could use another helper method Path.ChangeExtension:

string extension = ".jpg";
string fileName = Path.ChangeExtension(
    Path.GetRandomFileName(),
    extension
);

System.IO.Path.GetRandomFileName gets a file name that is guaranteed to be unique.

like image 165
Oleks Avatar answered Nov 20 '22 15:11

Oleks


As you want to save pictures, you could just use a GUID as the filename:

string filename = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".jpg");

I always do it this way when I need another file extension than .tmp (which files get when you create them via GetTempFileName).
Of course you could create the files via GetTempFileName and then rename them, but then you have to check again if a file with the new name exists...

like image 39
Christian Specht Avatar answered Nov 20 '22 14:11

Christian Specht


You could generate a Guid and use that for your file name. Although this would mean that the files are not human readable and have no information as to what the content is.

like image 4
Matt Avatar answered Nov 20 '22 16:11

Matt