Here's a utility class I've got to generate random passwords. It's similar to JohnIdol's Typing Monkey, but has a little more flexibility in case you want generated strings to contain uppercase, lowercase, numeric or special characters.
public static class RandomStringGenerator
{
private static bool m_UseSpecialChars = false;
#region Private Variables
private const int m_MinimumLength = 8;
private const string m_LowercaseChars = "abcdefghijklmnopqrstuvqxyz";
private const string m_UppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string m_NumericChars = "123456890";
private const string m_SpecialChars = "~?/@#!£$%^&*+-_.=|";
#endregion
#region Public Methods
/// <summary>
/// Generates string of the minimum length
/// </summary>
public static string Generate()
{
return Generate(m_MinimumLength);
}
/// <summary>
/// Generates a string of the specified length
/// </summary>
/// <param name="length">The number of characters to generate</param>
public static string Generate(int length)
{
return Generate(length, Environment.TickCount);
}
#endregion
#region Private Methods
/// <summary>
/// Generates a string of the specified length using the specified seed
/// </summary>
private static string Generate(int length, int seed)
{
// Generated strings must contain at least 3 of the following character groups: uppercase letters, lowercase letters
// numerals, and special characters (!, #, $, £, etc)
// The generated string must be at least 4 characters so that we can add a single character from each group.
if (length < 4) throw new ArgumentException("String length must be at least 4 characters");
StringBuilder SB = new StringBuilder();
Random rand = new Random(seed);
// Ensure that we add all of the required groups first
SB.Append(GetRandomCharacter(m_LowercaseChars, rand));
SB.Append(GetRandomCharacter(m_UppercaseChars, rand));
SB.Append(GetRandomCharacter(m_NumericChars, rand));
if (m_UseSpecialChars)
SB.Append(GetRandomCharacter(m_SpecialChars, rand));
// Now add random characters up to the end of the string
while (SB.Length < length)
{
SB.Append(GetRandomCharacter(GetRandomString(rand), rand));
}
return SB.ToString();
}
private static string GetRandomString(Random rand)
{
int a = rand.Next(3);
switch (a)
{
case 1:
return m_UppercaseChars;
case 2:
return m_NumericChars;
case 3:
return (m_UseSpecialChars) ? m_SpecialChars : m_LowercaseChars;
default:
return m_LowercaseChars;
}
}
private static char GetRandomCharacter(string s, Random rand)
{
int x = rand.Next(s.Length);
string a = s.Substring(x, 1);
char b = Convert.ToChar(a);
return (b);
}
#endregion
}
To use it:
string a = RandomStringGenerator.Generate(); // Generate 8 character random string
string b = RandomStringGenerator.Generate(10); // Generate 10 character random string
This code is in C# but should be fairly easy to convert to VB.NET using a code converter.