Probability of an Existing System.IO.Path.GetRandomFileName () File

I recently got an exception:

Message:
System.IO.IOException: The file 'C:\Windows\TEMP\635568456627146499.xlsx' already exists.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

This was the result of the following code that I used to create the file names:

Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks + ".xlsx");

Realizing that you can create two files in one tick, I changed the code to:

Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".xlsx");

But I'm still wondering what is the likelihood of this exception in the new case?

+4
source share
4 answers

Internally GetRandomFileNameused RNGCryptoServiceProviderto generate a string with 11 characters (name: 8 + ext: 3). The string represents the encoded base number 32, so the total number of possible strings is 32 11 or 2 55 .

, 2 -55 1 36 . : - .

+11

GetRandomFileName , , , t , ( , , )

Path.GetTempFileName Temp.
( )
GetTempFileName Win32 API GetTempFileName, .
API Win32 . , concurrency. .

+2

GetRandomFileName() 8.3 char. 11 , . , , "" 36 . , 36 ^ 11, .

+1

I would like to put my answer in the comments area, not here, but I don't have enough reputation to add a comment.

For your first snippet, I think you can check if the file exists or not.

For the second code, the code generates a random name, but random means that you still have a tiny opportunity to get an exception .... but I don’t think you need to worry about that. Checking for existence will help.

0
source

All Articles