How to generate a random string, and specify the length you want, or better generate unique string on specification you want

I can't recall where I got this, so if you know who originally authored this, please help me give attribution.

private static void Main()
{
    const string AllowedChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#@$^*()";
    Random rng = new Random();

    foreach (string randomString in rng.NextStrings(AllowedChars, (15, 64), 25))
    {
        Console.WriteLine(randomString);
    }

    Console.ReadLine();
}

private static IEnumerable<string> NextStrings(
    this Random rnd,
    string allowedChars,
    (int Min, int Max)length,
    int count)
{
    ISet<string> usedRandomStrings = new HashSet<string>();
    (int min, int max) = length;
    char[] chars = new char[max];
    int setLength = allowedChars.Length;

    while (count-- > 0)
    {
        int stringLength = rnd.Next(min, max + 1);

        for (int i = 0; i < stringLength; ++i)
        {
            chars[i] = allowedChars[rnd.Next(setLength)];
        }

        string randomString = new string(chars, 0, stringLength);

        if (usedRandomStrings.Add(randomString))
        {
            yield return randomString;
        }
        else
        {
            count++;
        }
    }
}

How about-

    static Random rd = new Random();
    internal static string CreateString(int stringLength)
    {
        const string allowedChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789!@$?_-";
        char[] chars = new char[stringLength];

        for (int i = 0; i < stringLength; i++)
        {
            chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
        }

        return new string(chars);
    }

I commonly use code like the following to generate a random string:

internal static class Utilities {
  static Random randomGenerator = new Random();
  internal static string GenerateRandomString(int length) {
    byte[] randomBytes = new byte[randomGenerator.Next(length)];
    randomGenerator.NextBytes(randomBytes);
    return Convert.ToBase64String(randomBytes);
  }
}

This will create a Base64 encoded string of the random bytes generated by the random object. It isn't thread safe so multiple threads will have to lock around it. Additionally I use a static Random object so two calls to the method at the same time won't get the same initial seed.

Tags:

C#

String

Random