13

I need to generate unique folder names, should I use Path.GetRandomFileName or just use Guid.NewGuid?

Guids say they are globally unique, GetRandomFileName does not make such a claim.

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Aran Mulholland
  • 23,555
  • 29
  • 141
  • 228
  • 4
    Guids are unique. GetRandomFileName depends on your machine being destroyed by a meteor having higher odds than the 1 in 1E17 odds of a name collision. Duck! – Hans Passant Mar 25 '14 at 18:51

1 Answers1

10

I think both are equally random, the difference being that Path.GetRandomFileName will produce a 8.3 filename (total of 11 characters) so is going to have a smaller set of unique names than those generated by Guid.NewGuid.

Max
  • 12,622
  • 16
  • 73
  • 101
NoviceProgrammer
  • 3,347
  • 1
  • 22
  • 32
  • according to the link (http://social.msdn.microsoft.com/Forums/vstudio/en-US/180b65dd-4c1d-4f2d-b02f-117db7afa7d9/why-use-pathgetrandomfilename-instead-of-guidnewguidtostring?forum=netfxbcl) the length is 11 char – Mzf Mar 25 '14 at 05:00
  • 1
    @Mzf: the example in msdn, returns `w143kxnu.idj`, so 11 random characters in the 8.3 format. Useful link though – NoviceProgrammer Mar 25 '14 at 05:09
  • I wonder what base GetRandomFileName uses (and thus the total output space) as it's not specified. What *is* specified, however, is that GetRandomFileName is "cryptographically strong", were a UUIDv4/GUID does not have such a claim. – user2864740 Mar 25 '14 at 05:14
  • 2
    The reference source for [System.IO.Path](http://referencesource.microsoft.com/#mscorlib/system/io/path.cs#efb113f637a6bb47) shows that they have a base32 scheme. Characters a-z and digits 0-5. So figure a namespace of 32^11, or 3.6e16. GUID is larger, true, but unless he's generating a whole lot of these files . . . – Jim Mischel Mar 25 '14 at 05:35
  • 2
    Oh, and GUID isn't *random*. It'll generate unique values although you have to use the whole thing. "No proper subsequence of the bits of a GUID have the global uniqueness property." See http://blogs.msdn.com/b/ericlippert/archive/2012/04/30/guid-guide-part-two.aspx – Jim Mischel Mar 25 '14 at 05:41
  • @user2864740: just looked at the function in ilspy and it uses a-z and 0-5 to build the names (32 char) – NoviceProgrammer Mar 25 '14 at 11:36
  • If generating hundreds of millions of unique filenames, which would you want to use? I am guessing GUID, i'm also wondering which is most performant.. – Darrell Nov 19 '20 at 08:56