Generate Random Code

Import below into your Namespace
using System.Security.Cryptography;
Declare Below Variables
public const string Alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public const string AlphaNumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
public const string Numeric = "1234567890";
Create a Enum as below
public enum StringType { Alpha, AplhaNumeric, Numeric }
Create a Method as below
public static string GenerateRandomCode(int CodeSize, StringType objStringType)
            string RandomCode = string.Empty;
                char[] chars = new char[62];
                if (objStringType == StringType.AplhaNumeric)
                    chars = AlphaNumeric.ToCharArray();
                else if (objStringType == StringType.Numeric)
                    chars = Numeric.ToCharArray();

                byte[] data = new byte[1];
                RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
                data = new byte[CodeSize];
                StringBuilder result = new StringBuilder(CodeSize);
                foreach (byte b in data)
                    result.Append(chars[b % (chars.Length - 1)]);
                RandomCode = result.ToString();
            catch (Exception ex)
                //throw ex;
            return RandomCode;

You can call the method using below code
Response.Write(GenerateRandomCode(4, StringType.Numeric));

Reference: Muthukumar (
Hope you liked this and let me know your thoughts on post through your comments :)


Twitter Delicious Facebook Digg Stumbleupon Favorites More