Mudassar
Mudassar

Reputation: 1576

Print Unique keys in C#.net

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

Answers (4)

Slappy
Slappy

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

Simon Mourier
Simon Mourier

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

Tobias Schittkowski
Tobias Schittkowski

Reputation: 2251

You could use the GUID class!

Every GUID is unique, even among other systems.

System.GUID.NewGuid().ToString()

Upvotes: 2

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

You can store existing generated keys and check if the new generated key is already generated or not.

Upvotes: 1

Related Questions