Monday, April 10, 2017

Sample C# program to generate a random string

You know well where it is required to generate a random string. It might be for a password generation or any other reason. Here is a sample C# program to generate a random string. You might required to pass a parameters length of the random string also a boolean param to say whether to include upper case characters.

/// 
/// Gets a random alphanumeric string of the specified length,
/// optionally using either all lowercase, or mixed lower and upper case.
/// 
/// Length of the string.
/// Whether to include uppercase characters.
public string GetRandomString(int length, bool includeUppercase)
{
    string chars = "abcdefghiklmnopqrstuvwxyz1234567890";
    if (includeUppercase) chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    StringBuilder sb = new StringBuilder(length);
    for (int chNum = 0; chNum < length; ++chNum)
    {
        int rand = this.GetRandomInt(0, chars.Length);
        sb.Append(chars[rand]);
    }

    return sb.ToString();
}


/// 
/// Gets a random boolean, based on the passed percentage.
/// It will return true in truePercentage percent of calls.
/// 
/// The percentage of the time true should be returned.
public bool GetRandomBoolean(int truePercentage)
{
    int rand = this.GetRandomInt(0, 100);  // [0-100), can be zero, can't be 100
    return (rand < truePercentage);
}

No comments:

Post a Comment