Will path.getrandomfilename generate a unique file

2019-02-22 02:53发布

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

2条回答
Root(大扎)
2楼-- · 2019-02-22 03:04

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

查看更多
小情绪 Triste *
3楼-- · 2019-02-22 03:10

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.

查看更多
登录 后发表回答