Uniquekey Generate Method
Code :
using System.Security.Cryptography;
import the above class for using the code
private string GetUniqueKey()
{
int maxSize = 8 ;
int minSize = 5 ;
char[] chars = new char[62];
string a;
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = a.ToCharArray();
int size = maxSize ;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data) ;
size = maxSize ;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size) ;
foreach(byte b in data )
{ result.Append(chars[b % (chars.Length - 1)]); }
return result.ToString();
}
Generation Method
|
Time Taken
|
Number of Generated
Keys
|
Number of Duplicate
Keys
|
All Fixed Length
Keys
|
|
Using DateTime and HashCode
|
01.56
sec
|
10,00,000
|
500131
|
No
|
|
Using GUIDs
and HashCode
|
04.45 sec
|
10,00,000
|
113
|
No
|
|
Using RNGCryptoServiceProvider
and Character Masking
|
00.40 sec
|
10,00,000
|
0 (Wow!!)
|
Yes
|
Using
DateTime and HashCode:
Using DateTime for generating unique keys is very common
practice. I have remixed this approach by inducing HashCode in it also. Like
Code :
DateTime.Now.ToString().GetHashCode().ToString("x");
Using
GUIDs and HashCode:
Code :
Guid.NewGuid().ToString().GetHashCode().ToString("x");
Guid.NewGuid().ToString().GetHashCode().ToString("x");
Comments
Post a Comment