Google


Earn money without investing 1$

lovebird-mails.com lovebird-mails.com

Wednesday, August 8, 2007

Random number generator function in c#

Hi All,
Some time we need to generate random sequence of alphanumeric /nemeric/character for password/key etc. Below is static function which takes integer as parameter for the length of the output.

private static string RandomNumberGenerator(int length)
{
RandomNumberGenerator rng = RandomNumberGenerator.Create();
char[] chars = new char[length];
string validChars = "abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ1234567890"; //based on your requirment you can take only alphabets or number
for (int i=0; i< length; i++)
{
byte[] bytes = new byte[1];
rng.GetBytes(bytes);
Random rnd = new Random(bytes[0]);
chars[i] = validChars[rnd.Next(0,61)];
}
return (new string(chars));
}

No comments:

Review Books

  • ASP.NET WebService
  • Learn VisualStudio.net
  • Basic .NET Framework
  • Basic C#
  • .NET Interview Questions
  • C# 2005 Programming