Will path.getrandomfilename generate a unique filename every time?
From : https://gist.github.com/samcorcos/e65a0f5a5d641dd3a6b5f513b6a911f8
const calculate = (n, k) => {
const exponent = (-k * (k - 1)) / (2 * n)
return 1 - Math.E ** exponent
}
// where `n` is the number of possible unique hashes
// where `k` is the number of values created
// calculate((26 + 10) ** 11, 51436220) => 0.010000000067703074
> Hit 1% chance of collision for 51,436,220 generated Path.GetRandomFileName
.
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
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.