Thursday, 24 March 2016

How to Generate 6 (Alphanumeric)Digits Random code in MVC and C#

How to Generate 6 (Alphanumeric)Digits Random code in MVC and C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;


public string GenerateVerifyCode()
        {
            int MAX_LENGTH = 6;
            char[] chrarrOTPChars = null;
            string strAlphaNum = null;
            byte[] btarrOTP = null;
            StringBuilder sbOTP = null;

            try
            {
                strAlphaNum = "abcdefghijklmnopqrstuvwxyz1234567890";
                chrarrOTPChars = new char[strAlphaNum.Length];
                chrarrOTPChars = strAlphaNum.ToCharArray();

                btarrOTP = new byte[1];
                RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
                crypto.GetNonZeroBytes(btarrOTP);
                btarrOTP = new byte[MAX_LENGTH];
                crypto.GetNonZeroBytes(btarrOTP);
                sbOTP = new StringBuilder(MAX_LENGTH);
                foreach (byte b in btarrOTP)
                { sbOTP.Append(chrarrOTPChars[b % (chrarrOTPChars.Length - 1)]); }
                return sbOTP.ToString();
            }
            catch (Exception oEx)
            {
                throw oEx;
            }
            finally
            {
                btarrOTP = null;
                strAlphaNum = null;
                chrarrOTPChars = null;
                sbOTP.Length = 0;
                sbOTP = null;
            }
        }

O/P:  6hjk7o
 

No comments: