C#: What is the fastest way to generate a unique filename?

前端 未结 8 1122
别那么骄傲
别那么骄傲 2020-12-23 20:42

I\'ve seen several suggestions on naming files randomly, including using

System.IO.Path.GetRandomFileName()

or using a

Sy         


        
8条回答
  •  伪装坚强ぢ
    2020-12-23 21:20

    A GUID would be extremely fast, since it's implementation guarantees Windows can generate at least 16,384 GUIDS in a 100-nanosecond timespan. (As others pointed out, the spec doesn't guarantee, only allows for. However, GUID generation is really, really fast. Really.) The likelihood of collision on any filesystem anywhere on any network is very low. It's safe enough that although it'd be best practice to always check to see if that filename is available anyway, in reality you would never even need to do that.

    So you're looking at no I/O operations except the save itself, and <0.2 milliseconds (on a test machine) to generate the name itself. Pretty fast.

提交回复
热议问题