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();
	bytes = new byte[size];
	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()
	bytes = New Byte(size - 1) {}
	Dim retVal = New StringBuilder(size)
	For Each b As Byte In bytes
		retVal.Append(allowedChars(b Mod (allowedChars.Length)))
	Return retVal.ToString()
End Function

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

Leave a Reply