I am attempting to write a random password generator. I am in the early stages and am running into a few problems. With the below code and screenshot you can see that I get a very predictable string (the string of 2's). Every time I receive a string filled with only one kind of number. How should I edit my code to generate a better password string? (other than including more than just numbers)

private void button1_Click(object sender, EventArgs e)
{
    int characters = Convert.ToInt32(comboBox1.SelectedIndex);
    string password = "";
    for(int i = 0; i <= characters; i++)
    {
       password = password +charGen();
    }
    label2.Text = password;
}
private char charGen()
{
    Random random = new Random();
    char randomNumber = Convert.ToChar( random.Next(48, 57));
    return randomNumber;
}
}
Just keep the random in the class scope:
Random random = new Random();
private void button1_Click(object sender, EventArgs e)
{
    int characters = Convert.ToInt32(comboBox1.SelectedIndex);
    string password = "";
    for(int i = 0; i <= characters; i++)
    {
       password = password +charGen();
    }
    label2.Text = password;
}
private char charGen()
{
    char randomNumber = Convert.ToChar( random.Next(48, 57));
    return randomNumber;
}
Currently it's seeded to practically the same value each time you call charGen.
The problem is that each time charGen is called, you create a new Random, which is initialized with the current clock for a seed. Since they are created so quickly, they all get the same seed.
You should create a single Random object at class level (or pass it to charGen).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With