Thursday, November 25, 2010

How to Generate Random String in C#, ASP.NET

To Generate a Random String is very Tricky and useful stuff to Know as we can use this functionality at the time of Generating Random Password automatically for each User Registering on the website.

I am sure this will help you a lot, here I am writing the Method to Generate the Random String.

private string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    }
Now the above code will generate the Random String. If you want to have a Strong Password then password must contains Number. So lets go to generate Random Numbers:
public string GetRandomNumber()
    {
        StringBuilder strbuild = new StringBuilder();
        strbuild.Append(RandomNumber(1000, 9999));
        return strbuild.ToString();
    }

private int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }

Now you are ready to generate a random password. for that you have to call these methods as given below:
public string GetPassword()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(4, true));
        builder.Append(RandomNumber(1000, 9999));
        builder.Append(RandomString(2, false));
        return builder.ToString();
    }

That's All, Please give your comments if the post is helpful.

No comments:

Post a Comment