How to generate Random Alphanumeric Strings in C# and VB.NET

To generate Random Alphanumeric Strings in C# and VB.NET you can use the following snippet.

Sample C#

public static string CreateRandomAlphanumericString(int size)
{
	var allowedChars = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
	var bytes = new byte[1];
	var crypto = new RNGCryptoServiceProvider();
	crypto.GetNonZeroBytes(bytes);
	bytes = new byte[size];
	crypto.GetNonZeroBytes(bytes);
	var retVal = new StringBuilder(size);
	foreach (byte b in bytes)
	{
		retVal.Append(allowedChars[b % (allowedChars.Length)]);
	}
	return retVal.ToString();
}

Sample VB.NET

Public Shared Function CreateRandomAlphanumericString(size As Integer) As String
	Dim allowedChars = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray()
	Dim bytes = New Byte(0) {}
	Dim crypto = New RNGCryptoServiceProvider()
	crypto.GetNonZeroBytes(bytes)
	bytes = New Byte(size - 1) {}
	crypto.GetNonZeroBytes(bytes)
	Dim retVal = New StringBuilder(size)
	For Each b As Byte In bytes
		retVal.Append(allowedChars(b Mod (allowedChars.Length)))
	Next
	Return retVal.ToString()
End Function

Please Share us:
Please rate this snippet

2 thoughts on “How to generate Random Alphanumeric Strings in C# and VB.NET

Leave a Reply