C# Random Password Generator -


here code: (passwordlengthbox numericupdown box, r , k random numbers)

    private void generatebutton_click(object sender, eventargs e)             {                 int r, k;                 int passwordlength = (int32)passwordlengthbox.value;                 string password = "";                 char[] uppercase = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };                 char[] lowercase = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };                 int[] numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };                 random rrandom = new random();                    (int = 0; < passwordlength; i++)                 {                     r = rrandom.next(3);                      if (r == 0)                     {                         k = rrandom.next(0, 25);                         password += uppercase[k];                     }                      else if (r == 1)                     {                         k = rrandom.next(0, 25);                         password += lowercase[k];                     }                      else if (r == 2)                     {                         k = rrandom.next(0, 9);                         password += numbers[k];                     }                  }                  textbox.text = password;             } 

what program create random password letters (both upper case , lower case) , numbers @ length choose. problem program not make password length chose.

for exemple: if type 5 in numericupdown box (passwordlengthbox) sets password length giving me passwords 5 chars long , sometime 6/7/8 chars long passwords.

what mistake?

problem here:

int[] numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; 

with declaration every time number appended password taken ascii number, not real value. you're adding integers 48 57, makes result string longer expected.

e.g. when 6 generated random number, you're appending like: ((int)'6').tostring() password variable, adds 54 instead of 6.

declare array char[] , works fine.


Comments