2

How to create random X-length string that contains letters and numbers. My fast solution is:

Guid.NewGuid().ToString("N").Substring(X);

Any another better ideas?

Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
  • 2
    http://stackoverflow.com/questions/1344221/how-can-i-generate-random-8-character-alphanumeric-strings-in-c – Henry Sep 19 '12 at 11:39

3 Answers3

2

GUIDs are not random, they are unique! If you are using them where randomness is required, you are doing something very wrong.

There are several options for random data generation, but the question here is: what is it meant for? Rolling dice? Encrypting state secrets?

Jon
  • 428,835
  • 81
  • 738
  • 806
  • In my case just to generate some random keys for dictionary. – Sergey Metlov Sep 19 '12 at 11:40
  • @DotNETNinja Why not just increment a number or use a Guid as-is? – Adam Houldsworth Sep 19 '12 at 11:42
  • @DotNETNinja: Well, since you want keys then you really *do not care* about their values; you only care that they are unique. Not random, just unique. So GUIDs would be a good choice, as would incrementing integers. – Jon Sep 19 '12 at 11:42
2

If you want "random" strings for dictionary keys, simply use a Guid. They will be unique and more than adequate for keying dictionaries.


Something like would work, but you need to constrain your random range to avoid shenanigans:

Warning, coded it and ran it once - otherwise untested. Performance versus your current solution is unquantified. Also, this implementation is a lot wordier than the answer linked in the question comments.

    static void Main(string[] args)
    {
        Random r = new Random();

        int x = r.Next(1, 1000);

        char[] pool = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
        char[] word = new char[x];

        for (int i = 0; i < x; i++)
        {
            // max value is not inclusive, so no -1 from length.
            int a = r.Next(pool.Length); 
            word[i] = pool[a];
        }

        Console.WriteLine(new string(word));
        Console.ReadLine();
    }

There's probably a nicer way to do this using the ASCII codes, but meh.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
1

I once made a "random" password generator and it looked like this. You can modify it as you please, and there's probably some room for linq expressions here.

public static string GeneratePassWord(bool useNumbers,bool useLetters, bool useUpperAndLowerCase, bool useSpecialCharacters, int passwordLength)
{
    Random randomNumber = new Random();
    List<char> chars = new List<char>();

    if (useNumbers) // Add numbers
    {
        for (int i = 0; i <= 9; i++)
        {
            chars.Add((char)(48 + i));
        }
    }

    if (useLetters) // Add letters
    {
        for (int i = 0; i <= 25; i++) // Small letters
        {
            chars.Add((char)(97 + i));
        }
        if (useUpperAndLowerCase)
        {
            for (int i = 0; i <= 25; i++) // Large letters
            {
                chars.Add((char)(65 + i));
            }
        }
    }

    if (useSpecialCharacters) // Add specials
    {
        chars.Add((char)'!');
        chars.Add((char)'#');
        chars.Add((char)'%');
        chars.Add((char)'&');
        chars.Add((char)'_');
        chars.Add((char)'.');
        chars.Add((char)'+');
        chars.Add((char)'@');
        chars.Add((char)'$');
    }

    // Generate random password from char
    if (chars.Count > 0)
    {
        StringBuilder newPass = new StringBuilder();
        for (int i = 0; i <= passwordLength; i++)
        {
            newPass.Append(chars[randomNumber.Next(chars.Count)]);
        }
        return newPass.ToString();
    }
    else
    {
        return string.Empty;
    }
}

As you see, it basically creates a List<> of chars, and then picks randomly from the list for each number of characters you want.

einord
  • 2,278
  • 2
  • 20
  • 26