How can I always generate a 17 character unique alphanumeric data with c#.
问题:
回答1:
Generate new Guid, and divide it 17 times by modulo 62. Each number you get is an index in char array described above ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890"). By using Guid you can guarantee that your value is as unique as Guid is.
If you are concerned with losing unique bits you may hash GUID with MD5 like this:
Guid guidValue = Guid.NewGuid();
MD5 md5 = MD5.Create();
Guid hashed = new Guid(md5.ComputeHash(guidValue.ToByteArray()));
UPDATE Guid format
According to this document (RFC 4122) and comparing with GUIDs generated by C#, they are of random type.
This type has the following pattern: xxxxxxxx-xxxx-4xxx-Vxxx-xxxxxxxxxxxx
, where
x
is random number andV
is a number with bit layout as 10yy, where yy are two random bits.
So, here we have 122 random bits out of 128. So, in terms of uniqueness the Guid is simply a large random number and you are free to use any other random-number-generation algorithm that is capable to produce 88-bit random number (for example RNGCryptoServiceProvider
).
Of course the method used to generate Guids may change in future versions of framework, but at the moment the Guid.NewGuid() looks like cheap random number generator in terms of code.
回答2:
You could try... http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx
The GetRandomFileName method returns a cryptographically strong, random string that can be used as either a folder name or a file name.
Or whatever you want.
回答3:
You can have hardcoded character set -
char[] chars = new char[62];
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ1234567890".ToCharArray();
Then using random number between 0 to 62, you can get random characters each time and append to your string.
However, you wont be able to guarantee that sometime down the lane, you will not be getting duplicate alphanumeric string too.
As an alternative, if possible, why dont you use GUID?