Random String Generator


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public class RandomStringGenerator
  2. {
  3. private Random r;
  4. const string UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  5. const string LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
  6. const string NUMBERS = "0123456789";
  7. const string SYMBOLS = @"~`!@#$%^&*()-_=+<>?:,./\[]{}|'";
  8.  
  9. public RandomStringGenerator()
  10. {
  11. r = new Random();
  12. }
  13.  
  14. public RandomStringGenerator(int seed)
  15. {
  16. r = new Random(seed);
  17. }
  18.  
  19. public virtual string NextString(int length)
  20. {
  21. return NextString(length, true, true, true, true);
  22. }
  23.  
  24. public virtual string NextString(int length, bool lowerCase, bool upperCase, bool numbers, bool symbols)
  25. {
  26. char[] charArray = new char[length];
  27. string charPool = string.Empty;
  28.  
  29. //Build character pool
  30. if (lowerCase)
  31. charPool += LOWERCASE;
  32.  
  33. if (upperCase)
  34. charPool += UPPERCASE;
  35.  
  36. if (numbers)
  37. charPool += NUMBERS;
  38.  
  39. if (symbols)
  40. charPool += SYMBOLS;
  41.  
  42. //Build the output character array
  43. for (int i = 0; i < charArray.Length; i++)
  44. {
  45. //Pick a random integer in the character pool
  46. int index = r.Next(0, charPool.Length);
  47.  
  48. //Set it to the output character array
  49. charArray[i] = charPool[index];
  50. }
  51.  
  52. return new string(charArray);
  53. }
  54. }

URL: http://www.vcskicks.com/random-string-generator.php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.