Pages

Saturday 4 August 2012

How to generate Random strings in Asp.Net?


Add this method to your Page. This method takes a parameter i.e. what is the size of the string you want to generate.   
    private readonly Random _rng = new Random();   
    private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private string RandomString(int size)
    {
        char[] buffer = new char[size];

        for (int i = 0; i < size; i++)
        {
            buffer[i] = _chars[_rng.Next(_chars.Length)];
        }
        return new string(buffer);
    }
Then, call this method wherever you want by passing the parameter as int.Here I am generating a new string each time I refresh the page. That's why I have called this method inside my Page_Load Event.
    protected void Page_Load(object sender, EventArgs e)
    {
        string ranNum =   RandomString(10);
        Response.Write(ranNum);
    }
Final Output:
Here, I am showing only five strings generated randomly by passing the parameter value "10" for size of the string.

Regards,
Prajanuranjan....


No comments:

Post a Comment

Total Pageviews