Question

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

Was it helpful?

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

OTHER TIPS

System.IO.Path.GetRandomFileName()

You can use the Path class in System.IO to, among other things, generate random file and folder names.

If you're using a database for your web site, then you can use an auto-incrementing number or a sequence to generate unique filenames for the images.

Using Oracle you would create a sequence as follows;

CREATE SEQUENCE sequence_name MINVALUE value MAXVALUE value START WITH value INCREMENT BY value CACHE value;

To get the next value in the sequence you use the nextval of the sequence. For example

CREATE SEQUENCE seq_user_id;

SELECT seq_user_id.NEXTVAL FROM dual;

INSERT INTO test_bed (user_id, class_type, room_location) VALUES (seq_user_id.NEXTVAL, 'Underwater Basketweaving', 'RM1205');

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top