How to generate a random string in c# 2.0

Although this is common knowledge to most dev’s,
I justed wanted to share some possible approaches for generating a random string in C#.

Approach 1: Create a static method in a utility class that will return a defined length of random characters.

One possible implementation could be:

static class Generator
{

private static Random _random = new Random();

public static string RandomString(int size)
{

StringBuilder builder = new StringBuilder();
for(int i=0; i < size; i++)
{

//26 letters in the alfabet, ascii + 65 for the capital letters
builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * _random.NextDouble() + 65))));

}
return builder.ToString();

}

}

Advantage:

  • can produce multiple length strings
  • can easily be updated to provide string with lowercase/uppercase/numbers in it

Approach 2: GUID

Just use a GUID if may contain numbers, letters and the character ‘-’
string randomString = Guid.NewGuid().ToString();

Advantage:

  • Simple, always unique

Disadvantage: always 36 chars in length

Approach 3 (humor): Be Lame
retard

Be lame and try the following

string randomString = System.IO.Path.ChangeExtension(System.IO.Path.GetRandomFileName(), null);

DisAdvantage: only produces strings of 8 characters and the idea is really way off…

Any one else fancy to post a (humorlike approach to a) random string generating solution ? ;)

7 Responses to “How to generate a random string in c# 2.0”

  1. Regarding your second approach. A Guid can be formatted when calling .ToString(). Example: Guid x = Guid.NewGuid();
    System.Diagnostics.Debug.WriteLine(”N: ” + x.ToString(”N”));
    System.Diagnostics.Debug.WriteLine(”D: ” + x.ToString(”D”));
    System.Diagnostics.Debug.WriteLine(”P: ” + x.ToString(”P”));
    System.Diagnostics.Debug.WriteLine(”B: ” + x.ToString(”B”)); produces Guid x = Guid.NewGuid();
    System.Diagnostics.Debug.WriteLine(”N: ” + x.ToString(”N”));
    System.Diagnostics.Debug.WriteLine(”D: ” + x.ToString(”D”));
    System.Diagnostics.Debug.WriteLine(”P: ” + x.ToString(”P”));
    System.Diagnostics.Debug.WriteLine(”B: ” + x.ToString(”B”));

  2. oops… copy pasted wrong… this is the output:
    N: a1e9332e94f14b2a87ddaeaeef4d205e
    D: a1e9332e-94f1-4b2a-87dd-aeaeef4d205e
    P: (a1e9332e-94f1-4b2a-87dd-aeaeef4d205e)
    B: {a1e9332e-94f1-4b2a-87dd-aeaeef4d205e}

  3. Nice, thanks.

  4. Hey

    Your statement

    builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * _random.NextDouble() + 65))));

    seems a little bit bad practice. What do you think about

    builder.Append((char)_random.Next(’A', ‘Z’ + 1));

    I think this is much more readable and much shorter. And by the way, for strings with lowercase letters, you don’t need a different methode. Just call:
    Generator.RandomString(NUMBER_OF_CHAR).ToLower()

    Have much fun
    Walter

  5. LINQ technique:

    Random rand = new Random();
    return new string(Enumerable.Repeat(0, 9).Select(i => (char)rand.Next(65, 90)).ToArray());

  6. how to rand insert words in string?

  7. Thx!
    I was looking for a way to generate a unique string in this format: ###-###-###-###

    With your first approach I now know how I can achieve this.

Leave a Reply