27
Mar
09

[VB.Net] RandomString Generator

Some guy on MSN asked me to write a function to generate random strings for him, here is the slightly modified result:

'''
''' A function to generate random strings
'''
''' An integer value between 0 and 2.
''' 0 returns a random string of numbers and letters, 1 returns a random string of letters and 2 returns a random string of numbers.
''' Any other value will return a random string of numbers and letters.
''' A random string of the desired length.
''' The length of the returned string.
''' http://simon.ctranter.co.uk
Private Function RandomString(ByVal Mode As Integer, ByVal StringLength As Integer) As String
    Dim randomG As New Random
    Dim randomN As Integer
    Const pwChars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Const pwNumbers As String = "0123456789"
    Dim str As String = ""
    While str.Length < StringLength
        If Not Mode = 1 And Not Mode = 2 Then
            randomN = randomG.Next(0, 2)
            If randomN = 0 Then
                randomN = randomG.Next(0, 26)
                str &= pwChars(randomN)
            Else
                randomN = randomG.Next(0, 10)
                str &= pwNumbers(randomN)
            End If
        ElseIf Mode = 1 Then
            randomN = randomG.Next(0, 26)
            str &= pwChars(randomN)
        ElseIf Mode = 2 Then
            randomN = randomG.Next(0, 10)
            str &= pwNumbers(randomN)
        End If
    End While
    Return str
End Function

Usage:

Debug.Write(RandomString(0, 25))

Would output:
32ECXD20AK9T1825832MZBWYG

Advertisements

0 Responses to “[VB.Net] RandomString Generator”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: