Generate random string using c#


Hi,
Today am blogging a simple concept related to generating a random sring. In realtime it will be used mainly for generating captcha, random password, Temporary objects etc.

Here we can send the string length expected. Also You can modify he complexity. Its a simple code and easily understandble. Here is the code snippet.

/// 
/// Creates the random string based on the length provided
/// 
/// Length of the password.
/// 
public static string generateRandomString(int PasswordLength)
{
  string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
  Random randNum = new Random();
  char[] chars = new char[PasswordLength];
  int allowedCharCount = _allowedChars.Length;

  for (int i = 0; i < PasswordLength; i++)
  {
    chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
  }
  return new string(chars);
}

hope it helps you.

Regards,
Pavan N

Comments

Popular posts from this blog

Implementing impersonation in c#

Generics in C# - Straight

Code Design - Choosing Abstract or Interface - Level 100