I've seen several suggestions on naming files randomly, including using
System.IO.Path.GetRandomFileName()
or using a
System.Guid
and appending a file extension.
My question is: What is the fastest way to generate a unique filename?
I've seen several suggestions on naming files randomly, including using
System.IO.Path.GetRandomFileName()
or using a
System.Guid
and appending a file extension.
My question is: What is the fastest way to generate a unique filename?
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.
That Guid method is pretty quick.
Since it is a good way to (very reasonably) ensure uniqueness, you avoid the need to check if the file exists.
(No HDD access) == (very fast, yes)
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.