Thursday, 5 April 2012

C# Generate Random String of a Specific Length

Today I came across a need of generating random string as a registration numbers in C# while  taking the participant information and generating a registration number of unique one. So to do it here is the code below.

public String generateRandomString(int length) {
    //Initiate objects & vars 
byte[ ] seed = Guid.NewGuid().ToByteArray();
Random random = new Random(BitConverter.ToInt32(seed,0));

    String randomString = "";
    int randNumber;

    //Loop ‘length’ times to generate a random number or character
    for (int i = 0; i < length; i++)            {
        if (random.Next(1, 3) == 1)  // here it is for taking 3 alphabets and all other numeric
             randNumber = random.Next(97, 123); //char {a-z}
        else
             randNumber = random.Next(48, 58); //int {0-9}

        //append random char or digit to random string
        randomString = randomString + (char)randNumber;
    }
    //return the random string
    return randomString;
}

1 comment:

  1. i not getting what is the use of if (random.Next(1, 3) == 1) statement.?

    ReplyDelete