Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create random folder names 12 characters long in .NET

I would like to create random folder names on my website to store images and their thumbnails, but instead of using the full version of a generated guid, i was thinking about using just part of it, maybe just the first 8 characters and possibly base64 encode it. i am worried about possible collisions though.

Can someone point me in the right direction as to whether or not it is a good enough idea? are there alternative solutions that can be used if i want to keep the name under a certain number of characters?

UPDATE: I am trying to stay away from path.GetRandomFileName , since it uses raw guid and it is not 12 chars long ...

like image 238
ak3nat0n Avatar asked Nov 29 '22 00:11

ak3nat0n


2 Answers

Why not just use something like this, and loop round until you can create the file without conflict?

 const string ValidChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

 static string GenerateName(Random random, int length)
 {
     char[] chars = new char[length];
     for (int i=0; i < length; i++)
     {
         chars[i] = ValidChars[random.Next(ValidChars.Length)];
     }
     return new string(chars);
 }

The reason for passing in the RNG is to avoid the typical problems of creating a new RNG in the method (duplicates when called in quick succession) while not using a static RNG (which isn't threadsafe).

An alternative would be to have a single static readonly RNG, and serialize calls within GenerateName by locking.

The main point is that somehow you generate a random name, and you just keep trying to create files with random names until you succeed, which is likely to happen very quickly (12 chars [A-Z 0-9] gives 4,738,381,338,321,616,896 possible combinations).

like image 110
Jon Skeet Avatar answered Dec 05 '22 00:12

Jon Skeet


System.IO.Path.GetRandomFileName()

like image 39
bsneeze Avatar answered Dec 04 '22 22:12

bsneeze