Tuesday, 27 November 2012

Random String Generator using Asp.net with C#



Using this class you can generate random strings like passwords and identificators, but the main feature is that you can customise it to fit your needs. To do that you don't need to modify the code, it's enough to set some settings and you'll change the behavior of the generator.

Write the following classes in your C# Page,
private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
private string RandomString(int size)
    {
        StringBuilder builder = new StringBuilder();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));                
            builder.Append(ch);
        }

        return builder.ToString();
    }

Then call the following method where ever you require,
// get random string where everyou require
string Rand = RandomString(4);

Enjoy the coding...

No comments:

Post a Comment