Search code examples
.netguidbase64auto-generate

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 ...


Solution

  • 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).