Generating random number and string in asp.net c#
Random class defined in the .NET Framework class library provides functionality to generate random numbers.
The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value, Random class has three public methods - Next, NextBytes, and NextDouble. Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0. The Next method has three overloaded forms and allows you to set the minimum and maximum range of the random number
Below is the class that generate random number, random string and calculate a random password just copy and paste this class and use these instance methods, call GetPassword() method to get a random password that contains combination string of 4 char size, number of 4 size and string of 2 chat size respectively.
The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value, Random class has three public methods - Next, NextBytes, and NextDouble. Next method returns a random number, NextBytes returns an array of bytes filled with random numbers, and NextDouble returns a random number between 0.0 and 1.0. The Next method has three overloaded forms and allows you to set the minimum and maximum range of the random number
Below is the class that generate random number, random string and calculate a random password just copy and paste this class and use these instance methods, call GetPassword() method to get a random password that contains combination string of 4 char size, number of 4 size and string of 2 chat size respectively.
Generating Random Number and String in C#
public class Random_Number
{
private
int RandomNumber(int
min, int max)
{
Random random = new
Random();
return random.Next(min, max);
}
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();
}
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();
}
}