Reputation: 1576
I am trying to make a key generator that generates upper case, lower case and numeric keys.
My current code below generates duplicates keys, using random numbers.
How could I update it to generate unique keys?
public static void printLowerCaseKeys()
{
string array = "";
int k = 0;
if (sDelimeterOption == "yes")
{
while (k < sKeyLength)
{
for (int i = 0; i < sDelimeterCharPosition; i++)
{
if (k >= sKeyLength)
break;
array = array + (char)r.Next(97, 123);
k++;
}
if (k < sKeyLength)
{
array = array + sDelimeterChar;
k++;
}
}
}
else
{
while (k < sKeyLength)
{
array = array + (char)r.Next(97, 123);
k++;
}
}
Console.WriteLine(array);
}
Upvotes: 1
Views: 137
Reputation: 4092
Guids are fine but if you want something more pretty looking (I.E.: Constrained in certain parts of the string) then you need to sort of do what you are doing, except you need to initialize your random object with a different seed. The best way to do this would be to use a portion of DateTime.Now (second, milliseconds or whatever)
Upvotes: 1
Reputation: 138960
Depending on the required key length, instead of using Random (if 'r' points to Random), you could base your random numbers on Guids (for 128-bit keys) or on what provides the RNGCryptoServiceProvider class.
Upvotes: 1
Reputation: 2251
You could use the GUID class!
Every GUID is unique, even among other systems.
System.GUID.NewGuid().ToString()
Upvotes: 2
Reputation: 18430
You can store existing generated keys and check if the new generated key is already generated or not.
Upvotes: 1