Will path.getrandomfilename generate a unique filename every time?

13,311

Solution 1

The short answer is yes in both cases.
In reality get it will generate 11 random chars that means there are (26 +10)^11 possible names (1.316217e+17) so chances of creating the same name twice are none existand for all practical purposes.

For more information I suggest you read this

and the relevant MSDN pages

Solution 2

On my system Path.GetRandomFileName() returns a short name in the 8.3 format.

Is it guaranteed never to return the same name twice? No, you can't guarantee that, just like you can't for any hashing algorithm either. There are only a finite amount of names so eventually you get a duplicate.

However the chance for that is very low since Path.GetRandomFileName() uses the RNGCryptoServiceProvider which is a cryptographically strong random number generator.

To summarize it, you can't guarantee in a strict way that it will be unique. But the chance for a duplicate is very low so you can assume it is.

Share:
13,311

Related videos on Youtube

SandhraPrakash
Author by

SandhraPrakash

Updated on June 05, 2022

Comments

  • SandhraPrakash
    SandhraPrakash almost 2 years

    Will Path.GetRandomFileName generate a unique filename every single time? Also, what about Path.GetTempFileName - will that generate a unique name?

    • CodesInChaos
      CodesInChaos over 10 years
      You'll get collisions at around a hundred million filenames. Depending on which collision probability you're willing to accept, it can become uncomfortable around a million filenames.
    • CodesInChaos
      CodesInChaos over 10 years
      Personally I'd use 128 bit random values instead of just 55 bit. May not fit 8.3 filenames, but DOS is pretty dead, so who cares?
    • rwong
      rwong over 8 years
      GetRandomFileName has a secondary motivation which is not entropy-related. Despite the NTFS supporting very long path names, most versions of .NET except the latest one are confined to MAX_PATH. In a lot of use cases, it is necessary to create several levels of randomized folders underneath the environmentally-defined TEMP folder. GetRandomFileName encodes the 50+ bits of entropy in a short name, which makes the path too long error less likely to happen. Other than that, I agree that one could probably follow the same logic and design a custom implementation that uses more entropy.
  • phuclv
    phuclv almost 5 years
    in fact there are only 32^11 possible names because GetRandomFileName() uses base 32 instead of base 36
  • George Birbilis
    George Birbilis over 3 years
    could retry till you get a non-existing one but could still have a data race with other threads (could make it a guarded block) and even worse with other procs