C# Generate Random String of a Specific Length - Code-Tips.com - Web Development, Programming, SEO

Tuesday, August 31, 2010

C# Generate Random String of a Specific Length

The following function will generate a random string of the supplied length.  The function uses the Random object to generate random integer values that correspond to ASCII values within a specific range (a-z, 0-9).  Once a random string has been generated that is the required length, it is then returned.



This can be useful if you are wanting to generate a unique code or id for use in a .NET application, or anything that supports C#.  For example, this could be used as an security code for authentication via links in an email.  The security code would be unique, and not be included in an email to more than one person.  The code can then be used to determine who clicked a link in an email by finding the user who corresponds to the unique code.

Another use may be for general logging/reporting of links clicked in an email to know who clicked a link when other tracking mechanisms are not available.  As the email address would need to be know to be able to send an email to the user, it is possible to have a unique code associated with every email that is distributed.



C#:
public String generateRandomString(int length) {
    //Initiate objects & vars    Random random = new Random();
    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)
             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;
}

4 comments:

  1. Thanks for the code. I ran into trouble getting random strings They seemed to repeat after a while. I added a line of code that uses a new Guid to create the seed:

    byte[] seed = Guid.NewGuid().ToByteArray();
    Random random = new Random(BitConverter.ToInt32(seed,0));

    I like to think this gives me a more random number.

    ReplyDelete
  2. The System.IO.Path has a static method(GetRandomFileName) which creates a random file name with 12 length.you can wrap this method in a custom class to create a random string with specific length

    happy .net coding
    Mehdi,Kiani

    ReplyDelete
  3. Hello

    I have a scenario that I need to generate a random email Id
    for the End User this random email will be linked to the Original Email of the User,
    now whenever anyone sends Email to the new random Email Id
    it automatically gets delivered to the Original Id as well.

    Thanks & Regards,

    ReplyDelete

Understood
This website is using cookies. More details