Search code examples
c#uniquefilenames

Safe to use random numbers to make filenames unique?


I'm writing a program which basically processes data and outputs many files. There is no way it will be producing more than 10-20 files each use. I just wanted to know if using this method to generate unique filenames is a good idea? is it possible that rand will choose, lets say x and then within 10 instances, choose x again. Is using random(); a good idea? Any inputs will be appreciated!

Random rand = new Random ();
int randNo = rand.Next(100000,999999)l

using (var write = new StreamWriter("C:\\test" + randNo + ".txt") 
{
// Stuff
}

Solution

  • I just wanted to know if using this method to generate unique filenames is a good idea?

    No. Uniqueness isn't a property of randomness. Random means that the resulting value is not in any way dependent upon previous state. Which means repeats are possible. You could get the same number many times in a row (though it's unlikely).

    If you want values which are unique, use a GUID:

    Guid.NewGuid();
    

    As pointed out in the comments below, this solution isn't perfect. But I contend that it's good enough for the problem at hand. The idea is that Random is designed to be random, and Guid is designed to be unique. Mathematically, "random" and "unique" are non-trivial problems to solve.

    Neither of these implementations is 100% perfect at what it does. But the point is to simply use the correct one of the two for the intended functionality.

    Or, to use an analogy... If you want to hammer a nail into a piece of wood, is it 100% guaranteed that the hammer will succeed in doing that? No. There exists a non-zero chance that the hammer will shatter upon contacting the nail. But I'd still reach for the hammer rather than jury rigging something with the screwdriver.