Wednesday, May 23, 2012

How to get random number and string in c#.net

Here i will show how to get the random  text from given user input in asp.net.The method GetRandomTextKey() has taken the length as parameter.The logic"minValue + rndValue * randomRange" has used to generate a random text.Asp.net provide a class which Rnadom is used in this process
 public static string GetRandomTextKey(int length)
    {
        Random rnd = new Random((int)System.DateTime.Now.Ticks);
        System.Text.StringBuilder randomText = new
        System.Text.StringBuilder(length);

        int minValue = 65;
        int maxValue = 90;
        int randomRange = maxValue - minValue;

        double rndValue;
        for (int i = 0; i < length; i++)
        {
            rndValue = rnd.NextDouble();
            randomText.Append((char)(minValue + rndValue * randomRange));
        }

        return randomText.ToString();
    }
              

No comments:

Bel