The substring of GUID is not unique

Jul 23, 2012 at 6:24 AM
Edited Jul 23, 2012 at 6:26 AM

In this project, the random string is generated by  following code:

Guid newguid = Guid.NewGuid();

string randomStr =            newguid.ToString("N");

string tracStr = randomStr.Substring(0,            (int)keyLength);

GUID is a unique sting, but the substing of GUID is not always unique.

Jul 23, 2012 at 9:03 AM

I discoveried another issue. The key generated by substring of Guid only contains 0~9 and A~F.

I changed the algorithm which from the stackoverflow.

var random = new Random();
var result = new string(
Enumerable.Repeat(chars, 8)
.Select(s => s[random.Next(s.Length)])