Import below into your Namespace
You can call the method using below code
Reference: Muthukumar (http://nadarmuthukumar.blogspot.in)
Hope you liked this and let me know your thoughts on post through your comments :)
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; try { 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(); crypto.GetNonZeroBytes(data); data = new byte[CodeSize]; crypto.GetNonZeroBytes(data); 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 (http://nadarmuthukumar.blogspot.in)
Hope you liked this and let me know your thoughts on post through your comments :)
0 comments:
Post a Comment