Sunday, 3 March 2013

Generate Random String using VB.NET


Generate Random String using VB.NET


This tutorial generates Random Strings may be suitable for Password generation/Captcha etc.,

// This example uses Random class generates sequence of bytes and then converts those bytes to
//String, picks only Alphabets.
//
        Private Function GenerateRandomString() As String           
           Dim bytes() As Byte =  New Byte(255) {}
            rnd.NextBytes(bytes)
            Dim szRandom As String =  System.Text.Encoding.ASCII.GetString(bytes)
            Dim c() As Char =  szRandom.ToCharArray()
            Dim sb As StringBuilder =  New StringBuilder()
            Dim cc As Char
            For Each cc In c
                If Char.IsLetter(cc) Then
                    sb.Append(cc)
                End If
            Next
            Return sb.ToString()
        End Function
 
Dim rnd As Random =  New Random
Console.WriteLine("RandomPassword={0}",GenerateRandomString());

Output:
RandomPassword=WTdavEYQqzBekgKkqgJalgQGsgSJVdiQgnJzwwrlbJe
RandomPassword=dJpjgBczezrQSMLzkYhLoZRJdStitRFoHdmJikqhfGcxlrniKChEkI
RandomPassword=DGaYmSvZuHoHRMjVfvQrrVzxoDiQdvwkjDgKjAQXRGUEx
RandomPassword=mZABWuDFUHHEzVVmSchQHFnbOfXPpBMcxRfrFKqtzvJNTnurjHYz
RandomPassword=IzYTMyvMpmNaDqXRNFVtIgnHfVVEioYbUTkyIRSASDvbgcGoYlJBpuqp
RandomPassword=SLkyLRSLhDOkXztdIGIOVRkjqwTdfkqYUMQszCtnTNWiwcWVPngmBxRge


For Random AlphaNumeric  Strings


Change the Logic to
   Char.IsLetterOrDigit(cc)

Output:a6Nna0eeJaXW2K8LNAfBMTBmgSd2YoezGODa1v37sWlsAlL19CpQwkGVdDmdwIdzKbX

For Random Numbers.

  U can use same Random class,Each time it generates new number, otherwise,
Chanage the Logic like this
Char.IsNumber(cc)
Output:
2752175506
6767
578799
89989878
Tags:    Generate Random String using VB.NET,Generate Random Passwords,Generate Random Numbers VB.NET, Random String Vb.NET,Generate Random Alphanumeric String VB.NET,How to Generate Random String in VB.NET

No comments:

Post a Comment