How to create a random string of characters in C#?

Posted by Keltex on Stack Overflow See other posts from Stack Overflow or by Keltex
Published on 2010-04-01T20:49:45Z Indexed on 2010/04/01 20:53 UTC
Read the original article Hit count: 328

Filed under:
|

I'm trying to create random strings of characters. I'm wondering if there might be a more efficient way. Here's my algorithm:

string RANDOM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#@$^*()";

StringBuilder sb = new StringBuilder();
int length = rand.Next(10) + 1;

for (int idx = 0; idx < length; ++idx)
{
    sb.Append(RANDOM[rand.Next(RANDOM.Length)]);
}

string RandomString = sb.ToString();

I'm wondering if the StringBuilder is the best choice. Also if selecting a random character from my RANDOM string is the best way.

© Stack Overflow or respective owner

Related posts about c#

Related posts about algorithm