08 May 2013

Generate a random password in C#

There are always need of some common functions in many projects. One of them is random password generation. .NET framework is rich set of in-built functions which are mean to solve some general issues. For the random password generation, there is already in-built function is provided in the .NET framework i.e. Membership.GeneratePassword (NameSpace : System.Web.Security). You can get more details about Membership.GeneratePassword  here

However that function is not fit in each situation. So I have generate one new function which creates password with alpha-numeric values.


public string GetRandomPassword()
{
  string randomChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

  char[] randomElements = randomChars.ToCharArray();

  Random r = new Random();

  StringBuilder builder = new StringBuilder();
  for(int i = 0; i=6; i++)
  {
     int randomChar = r.Next(0, randomElements.Length);
     builder.Append(randomElements[randomChar]);
  }
   return builder.ToString();
}

Above function will generate a random password with alphanumeric values. Length of the password will be 6. For the beginner level users,below is the steps of the functions in order to understand it easily.


  1. Declare a string variable with alphanumeric values and convert it to character array.
  2. With use of Random type variable, loop through 6 times(or up to your requirement) to create 6 character long password in StringBuilder.
  3. Return builder string will give the random password.
Hope this small piece code of will help you to create random password with C#