none
VB.NET Generate a random string of numbers and letters

Answers


  • Here is the basic idea.  If you want upper and lower case letters, then add the lower case letters to the string s.
     
        Sub Main()
            Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            Dim r As New Random
            Dim sb As New StringBuilder
            For i As Integer = 1 To 8
                Dim idx As Integer = r.Next(0, 35)
                sb.Append(s.Substring(idx, 1))
            Next
            Console.WriteLine(sb.ToString())
            Console.ReadKey()
        End Sub
     
     

    --
    Mike
    • Marked as answer by Xakepa Saturday, July 17, 2010 4:03 PM
    Saturday, July 17, 2010 4:01 PM

All replies


  • Here is the basic idea.  If you want upper and lower case letters, then add the lower case letters to the string s.
     
        Sub Main()
            Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            Dim r As New Random
            Dim sb As New StringBuilder
            For i As Integer = 1 To 8
                Dim idx As Integer = r.Next(0, 35)
                sb.Append(s.Substring(idx, 1))
            Next
            Console.WriteLine(sb.ToString())
            Console.ReadKey()
        End Sub
     
     

    --
    Mike
    • Marked as answer by Xakepa Saturday, July 17, 2010 4:03 PM
    Saturday, July 17, 2010 4:01 PM
  • How can I implement this into a Windows Froms Application. I need it as a dim value.

    Saturday, July 17, 2010 4:04 PM
  • uppercase, lowercase or both?

    can letters/numbers repeat or not?

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Letters As New List(Of Integer)
        'add ASCII codes for numbers
        For i As Integer = 48 To 57
          Letters.Add(i)
        Next
        'lowercase letters
        For i As Integer = 97 To 122
          Letters.Add(i)
        Next
        'uppercase letters
        For i As Integer = 65 To 90
          Letters.Add(i)
        Next
        'select 8 random integers from number of items in Letters
        'then convert those random integers to characters and
        'add each to a string and display in Textbox
        Dim Rnd As New Random
        Dim SB As New System.Text.StringBuilder
        Dim Temp As Integer
        For count As Integer = 1 To 8
          Temp = Rnd.Next(0, Letters.Count)
          SB.Append(Chr(Letters(Temp)))
        Next
    
        Label1.Text = SB.ToString
      End Sub
    
      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Label1.Font = New Font("Arial", 14)
      End Sub
    
    Saturday, July 17, 2010 4:07 PM

  • The code would be the same, except I guess you want a function:
     
    Functon GeneratePassword()
            Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            Dim r As New Random
            Dim sb As New StringBuilder
            For i As Integer = 1 To 8
                Dim idx As Integer = r.Next(0, 35)
                sb.Append(s.Substring(idx, 1))
            Next

            return sb.ToString()
    End Function
     

    --
    Mike
    Saturday, July 17, 2010 4:10 PM
  • Here is a function I just wrote that will do this.  You can update the string array so that it will only use characters you want.  You can also specify the length when calling it:

    In your case from a WinForm, you could see a message box of the values it creates with this code:

        MsgBox(RandomString(8))
    
     ''' <summary>
     ''' Returns a random string of the specified length. 
     ''' </summary>
     ''' <param name="length"></param>
     ''' <returns></returns>
     ''' <remarks>
     ''' All supported characters are contained in the chars() string array. Characters can be added or removed from this array to
     ''' add or remove them from inclusion when the random string is created.
     ''' bpell
     ''' </remarks>
     Public Function RandomString(ByVal length As Integer) As String
      Dim sb As New System.Text.StringBuilder
      Dim chars() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", _
             "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "X", _
             "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}
      Dim upperBound As Integer = UBound(chars)
    
      For x As Integer = 1 To length
       sb.Append(chars(Int(Rnd() * upperBound)))
      Next
    
      Return sb.ToString
    
     End Function
    
    Saturday, July 17, 2010 4:11 PM
  • jwavila's code shows me I goofed on the value using the random function.  Use the following line to find idx in my code:
     
    dim idx as integer = r.Next(0, s.Length)

     

    --
    Mike
    Saturday, July 17, 2010 4:12 PM
  • Let me add this also: If you want it to be truly unique (or veritably no possibility of there being another one just like it), embed the date and time (to the second) in it. Between that and the random, I can't imagine it not to be unique.
    Saturday, July 17, 2010 4:15 PM
  • Hehe, look at all the answers before I got my post finished. :)  Gotta love the community response time.  :)
    Saturday, July 17, 2010 4:15 PM
  • This is the only one that worked for me. Any idea how to exclude individual numbers and letters?


    Friday, March 29, 2013 11:39 AM
  • Mike, I am just dropping in to let you know that your posting is useful to me. Here is my code:

    '--------------------------------------------------------------------------------------
    ' Class to generate 8-letter string in upper case, generation is by random, uniqueness 
    ' by keeping generated values in a list - scope of uniquness is within object instance.
    '--------------------------------------------------------------------------------------
    
    Imports System.Text
    
    Public Class UniqueRandomString
    
        Dim allocated As List(Of StringBuilder) = New List(Of StringBuilder)
    
        Public Function generate() As String
            Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
            Dim r As Random = New Random
            Dim sb As StringBuilder = New StringBuilder
            Do
                For i As Integer = 1 To 8
                    Dim idx As Integer = r.Next(0, 35) '26 letters + 10 digits
                    sb.Append(s.Substring(idx, 1))
                Next
            Loop Until Not allocated.Contains(sb)
            allocated.Add(sb)
            Return sb.ToString()
        End Function
    
    End Class

    Usage example:

    Dim URS8 as UniqueRandomString = New UniqueRandomString
    Console.WriteLine(URS8.generate())

    Result: Expect to output an 8 letter-wide unique string.

    Note: The string is unique ONLY to the object URS8. That is, repeating calling URS8.generate() will generate a different string until all the permutations had been exausted.

    Further considerations: After a large number of call to URS8.generate() performance will degrade due to growing size of the list. When permutatiions have been exhausted the do-loop will deadlock.



    • Edited by coarist Saturday, June 29, 2013 12:58 AM Correction "for" changed to "do"
    Saturday, June 29, 2013 12:55 AM
  • Here is far much better code that will allow you to not only generate random numbers and letters but also special characters... You type in the beginning how long do you want your password to be and it will take that number and give you the password.... Enjoy the results...

    -------------------------------------------------------------------------------------------------------------------------------

    Public Class frmPassGen

        Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click
            On Error Resume Next
            ' exit program
            Me.Close()
            End
        End Sub

        Private Sub cmdClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdClear.Click
            On Error Resume Next
            txtPassword.Text = ""
            txtLenPass.Text = ""
            txtLenPass.Focus()
        End Sub

        Private Sub cmdOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOK.Click
            On Error Resume Next
            Dim Letters As New List(Of Integer)
            'add ASCII Codes for Numbers
            For i As Integer = 48 To 57
                Letters.Add(i)
            Next
            'Lower Case
            For i As Integer = 97 To 122
                Letters.Add(i)
            Next
            'Upper Case
            For i As Integer = 65 To 90
                Letters.Add(i)
            Next
            'Special Characters
            For i As Integer = 33 To 42
                Letters.Add(i)
            Next
            'Select 8 to 12 random integers from number of itesm in Letters
            'Convert those random integers to characters and
            'Add each to string to display in txtPassword.text

            Dim Rnd As New Random
            Dim SB As New System.Text.StringBuilder
            Dim Temp As Integer
            For count As Integer = 1 To Val(txtLenPass.Text)
                
                Temp = Rnd.Next(0, Letters.Count)
                SB.Append(Chr(Letters(Temp)))

            Next
            txtPassword.Text = SB.ToString

        End Sub

    End Class

    • Proposed as answer by calfasoft Saturday, March 05, 2016 5:09 PM
    • Unproposed as answer by calfasoft Saturday, March 05, 2016 5:09 PM
    Wednesday, August 27, 2014 9:35 PM
  • ho preso spunto dalle risposte ed ho creato una funzione più flessibile 

    Function Genera_Stringa(ByVal LUNGHEZZA As Integer, Optional TIPO As String = "A") As String
    
      ' DEFINIZIONE TIPO 
      ' 0 : numeri
      ' A : lettere maiuscole
      ' a : lettere minuscole
      Dim Letters As New List(Of Integer)
    
      If InStr(TIPO, "0") Then 'add ASCII codes for numbers
       For i As Integer = 48 To 57
        Letters.Add(i)
       Next
      End If
    
      If InStr(TIPO, "a") Then 'add ASCII codes for lowercase letters
       For i As Integer = 97 To 122
        Letters.Add(i)
       Next
      End If
    
      If InStr(TIPO, "A") Then 'add ASCII codes for uppercase letters
       For i As Integer = 65 To 90
        Letters.Add(i)
       Next
      End If
    
      'select "LUNGHEZZA" random integers from number of items in Letters then convert those random integers to characters and add each to a string and return
      Dim Rnd As New Random
      Dim SB As New System.Text.StringBuilder
      Dim Temp As Integer
      For count As Integer = 1 To LUNGHEZZA
       Temp = Rnd.Next(0, Letters.Count)
       SB.Append(Chr(Letters(Temp)))
      Next
    
      Genera_Stringa = SB.ToString
    
     End Function



    • Edited by calfasoft Saturday, March 05, 2016 5:11 PM
    Saturday, March 05, 2016 5:09 PM
  • Here's another solution, using ASCII values and a listbox to display the 8 random characters:

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            ListBox1.Items.Clear()
            Dim randnum As New Random
            Dim Anum As Integer
            Dim mychar As Char
            For x As Integer = 1 To 8
                Anum = randnum.Next(0, 61)
                Select Case Anum
                    Case 0 To 9    'digits
                        mychar = Chr(Anum + 48)
                    Case 10 To 35   'uppercase letters
                        mychar = Chr(Anum + 55)
                    Case Else       'lowercase letters
                        mychar = Chr(Anum + 62)
                End Select
                If ListBox1.Items.Contains(mychar) Then
                    x = x - 1       'repeat to select a different random number so no duplicates listed
                Else
                    ListBox1.Items.Add(mychar)
                End If
            Next x
        End Sub
    Note:  To use only digits and uppercase letters, change the randnum.Next argument to (0, 36) and omit the Case Else.


    Solitaire



    • Edited by Solitaire Saturday, March 05, 2016 6:14 PM
    Saturday, March 05, 2016 6:07 PM
  • Just some additional info to consider...

    Depending on how quickly you call the password generation method in succession, all of the proposed solutions thus far are subject to generating the exact same password repeatedly.  This is because all of the methods declare the pseudo random number generator within the method body and without a variable seed value.  So, if the method is called rapidly enough in succession, each call will use the same date/time value when seeding the random number generator.  On a fast computer, calling the password generation method 10,000 times in a loop could result in as few as four unique passwords.  This is because the code runs so quickly that there is not enough time elapsed to get a new seed value for the random number generator.

    One way to address this is to put the functionality within its own class so that you can have a single instance of Random which is used by each call to generate a new password.  This way you wouldn't be creating a new Random object every time the method was called.  In other words, move the Random instance declaration out of the method body.

    Another option would be to generate a random series of characters without full dependence on the pseudo random number generator.  This could be done by generating a GUID, encoding it to Base64, then taking the first eight alphanumeric characters from the resulting string.  Because the initial source of random values is based on a GUID, there is very little chance of generating the same set of values twice in a row regardless of how quickly you make those two calls.

    Here is a simple example of this idea:

    Private Function GetRandomPassword() As String
        Dim pwdChars As New System.Text.StringBuilder
        Dim tmpId = Guid.NewGuid
        Dim b64 = Convert.ToBase64String(tmpId.ToByteArray)
        For Each c In b64
            If Char.IsLetterOrDigit(c) Then
                pwdChars.Append(c)
                If pwdChars.Length = 8 Then Exit For
            End If
        Next
        Return pwdChars.ToString
    End Function
    

    This method can be called 1,000,000 times in succession without creating a duplicate password.  Now, technically you should be using all 20-ish characters (or include the + and = characters and use all 22) to get the full probability of unique values.  By only using the first 8 characters you could eventually generate a duplicate password, but the chances are still very low that a duplicate would be generated in a short amount of time.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Saturday, March 05, 2016 9:02 PM
    Moderator
  • Nowhere does the op mention a password.  S/he only wanted a string of 8 unique characters.

    Solitaire

    Saturday, March 05, 2016 10:39 PM
  • You can safely replace the word "password" with "string" when reading my post.  The information still applies; it's probably not a good idea to create a new Random instance on every method call without explicitly setting the seed.  That is generally true regardless of how the Random instance is being used.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Saturday, March 05, 2016 11:01 PM
    Moderator