Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will path.getrandomfilename generate a unique filename every time?

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

like image 792
SandhraPrakash Avatar asked Feb 10 '14 18:02

SandhraPrakash


3 Answers

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.

like image 124
Dirk Avatar answered Nov 13 '22 21:11

Dirk


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

like image 26
Sibster Avatar answered Nov 13 '22 21:11

Sibster


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.

like image 1
Valentin P Avatar answered Nov 13 '22 20:11

Valentin P