I've tried this before, and the performance wasn't that great. Regex is one way to do it. I'm all for regex, but using it in this sense is over-engineering.
Make an array with all the characters you want to use, and then randomly cycle through it grabbing a single element at a time (or a group with element displacement) and you should be good to go.
Here's a sample program you can copypasta or peruse. I'd be very interested to know the performance difference between @Access Denied's answer, and this little guy. Pardon the lack of elegance, but I was going to clarity in case someone else stumbles upon this.
using System;
using System.Text;
namespace RandomString
{
class Program
{
static void Main()
{
Console.WriteLine("My new random alphanumeric string is {0}", GetRandomAlphaNumString(12));
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey(true);
}
static char[] charactersAvailable = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
public static string GetRandomAlphaNumString(uint stringLength)
{
StringBuilder randomString = new StringBuilder();
Random randomCharacter = new Random();
for (uint i = 0; i < stringLength; i++)
{
int randomCharSelected = randomCharacter.Next(0, (charactersAvailable.Length - 1));
randomString.Append(charactersAvailable[randomCharSelected]);
}
return randomString.ToString();
}
}
}