Sunday, 3 March 2013

Generate Random String using C#

Generate Random String using C#


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.
//
        String GenerateRandomString()
        {            
           byte[] bytes = new byte[255];
            rnd.NextBytes(bytes);
            String szRandom = System.Text.Encoding.ASCII.GetString(bytes);
            char[] c = szRandom.ToCharArray();
            StringBuilder sb = new StringBuilder();
            foreach (char cc in c)
            {
                if (Char.IsLetter(cc))
                {
                    sb.Append(cc);
                }
            }            return sb.ToString(); ;
        }
Random rnd = 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 C#,Generate Random Passwords,Generate Random Numbers C#, Random String C#,Generate Random Alphanumeric String C#,How to Generate Random String in C#