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

前端 未结 8 1118
别那么骄傲
别那么骄傲 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:38

    If you control the destination where the files will be located, and there is only one process and thread that writes to it, just append some auto-incrementing number to a base name.

    If you don't control the destination, or need a multithreaded implementation, use a GUID.

    0 讨论(0)
  • 2020-12-23 21:39

    Well I have been writing file system drivers for 20 years and would say Rex is correct. Generating a guid is much much faster, since it requires far less overhead than searching for a unique file name. GetTempFileName actually creates a file, which means it has to call through the entire file system driver stack (who knows how many calls that would be and a switch into kernel mode.) GetRandomFileName sounds like it is faster, however I would trust the GUID call to be even faster. What people don't realize is that even testing for the existence of a file requires a complete call through the driver stack. It actually results in an open, get attributes and close (which is at least 3 calls, depending on the level.) In reality it is a minimum of 20 function calls and a transition to kernel mode. GUIDS guarentee of uniqueness is good enough for most purposes.

    My recommendation is to generate the name and create the file only if it doesn't exist. If it does, throw an exception and catch it, then generate a new guid and try again. That way, you have zero chance of errors and can sleep easy at night.

    On a side note, checking for errors is so overdone. Code should be designed to crash if assumptions are wrong, or catch exceptions and deal with it then. Its much faster to push and pop and address on the exception stack, than to check everytime on every function for an error.

    0 讨论(0)
提交回复
热议问题