How can I generate random 8 character alphanumeric strings in C#?
I heard LINQ is the new black, so here's my attempt using LINQ:
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var result = new string(
Enumerable.Repeat(chars, 8)
.Select(s => s[random.Next(s.Length)])
.ToArray());
This implementation (found via google) looks sound to me:
using System.Security.Cryptography;
using System.Text;
namespace UniqueKey
{
public class KeyGenerator
{
public static string GetUniqueKey(int maxSize)
{
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
data = new byte[maxSize];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(maxSize);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length - 1)]);
}
return result.ToString();
}
}
}
Picked that one from a discussion of alternatives here
Not as elegant as the Linq solution. (-:
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
Here's an example that I stole from Sam Allen example at Dot Net Perls
If you only need 8 characters, then use Path.GetRandomFileName() in the System.IO namespace. Sam says using the "Path.GetRandomFileName method here is sometimes superior, because it uses RNGCryptoServiceProvider for better randomness. However, it is limited to 11 random characters."
GetRandomFileName always returns a 12 character string with a period at the 9th character. So you'll need to strip the period (since that's not random) and then take 8 characters from the string. Actually, you could just take the first 8 characters and not worry about the period.
public string Get8CharacterRandomString()
{
string path = Path.GetRandomFileName();
path = path.Replace(".", ""); // Remove period.
return path.Substring(0, 8); // Return 8 character string
}
PS: thanks Sam
Why not just use a Guid?
Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 8);
Just tested with 100,000 iterations, generated only one duplicate.
Edit: Technically you do not need the call to .Replace. The dash comes after the first 8 characters in a Guid. I’m used to having to generate 16 char random numbers for a project I work on. Should be:
Guid.NewGuid().ToString().Substring(0, 8);
Horrible, I know, but I just couldn't help myself:
namespace ConsoleApplication2
{
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
while (!Regex.IsMatch((c=Convert.ToChar(adomRng.Next(48,128))).ToString(), "[A-Za-z0-9]"));
rndString += c;
}
Console.WriteLine(rndString + Environment.NewLine);
}
}
}
- If you don't need a cryptographically random generator
- If you know the length of the output, you don't need a StringBuilder, and when using ToCharArray, this creates and fills the array (you don't need to create an empty array first)
- You should use NextBytes, rather than getting one at a time for performance
- Technically you could pin the byte array for faster access.. it's usually worth it when your iterating more than 6-8 times over a byte array.
- Define your character set and Random gen object once.
- My example has a 62 char set and 32 char output
Clearly, you can adjust this example, to accept the string length as a param.
private static char[] charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray(); private static Random rGen = new Random(); public string GenerateRandomString() { byte[] rBytes = new byte[32]; rGen.NextBytes(rBytes); char[] rName = new char[32]; for (int i = 0; i < 32; i++) rName[i] = charSet[rBytes[i] % 62]; return rName.ToString(); }
If your values are not completely random, but in fact may depend on something - you may compute an md5 or sha1 hash of that 'somwthing' and then truncate it to whatever length you want.
Also you may generate and truncate a guid.