2/01/2016

C# User Defined RandomStringGenerator()


public partial class Signup : System.Web.UI.Page
{
   private string GenAuthCode(string username)
    {
        RandomStringGenerator myrsg = new RandomStringGenerator();
        return myrsg.NextString(20);
    }
}
public class RandomStringGenerator
{
    private Random r;
    const string Uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const string Lowercase = "abcdefghijklmnopqrstuvwxyz";
    const string Numbers = "0123456789";
    const string Symbols = @"~`!@#$%^&()-_=+<>?:,./\[]{}'";
    public RandomStringGenerator()
    {
        r = new Random();
    }
    public RandomStringGenerator(int seed)
    {
        r = new Random(seed);
    }
    public virtual string NextString(int Length)
    {
        return NextString(Length, true, true, true, true);
    }
    public virtual string NextString(int Length, bool lowerCase, bool upperCase, bool numbers, bool symbols)
    {
        char[] charArray = new char[Length];
        string charpool = string.Empty;

        //Build character pool
        if (lowerCase)
            charpool += lowerCase;
        if (upperCase)
            charpool += upperCase;
        if (numbers)
            charpool += numbers;
        if (symbols)
            charpool += symbols;

        //Build the output character array
        for (int i = 0; i < charArray.Length; i++)
        {
            //Pick the randim integer in the character pool
            int index = r.Next(0, charpool.Length);

            //Set it to the output character array
            charArray[i] = charpool[index];
        }
        return new string(charArray);

    }
}