Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a keygen that writes "-" every four letters in C#

I have a quick question. I have a keygen to generate random passwords for my app. It generates capital letters and numbers but I want it to be like in some programs that formats their code like this xxxx-xxxx-xxxx. so far my code is this

Random random = new Random(0);

private void button1_Click(object sender, EventArgs e)
{
    textBox1.Text = getrandomcode();
}

public string getrandomcode()
{
    char[] tokens = {'0', '1', '2', '3', '4', '5', '7', '8', '9', '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[] codeArray = new char[24];

    for (int i = 0; i < 24; i++)
    {
        int index = random.Next(tokens.Length - 1);
        codeArray[i] = tokens[index];
    }

    return new String(codeArray);
}

Its something simple not to complex so I hope there is a way to implement the "-" to this code.

thanks in advance!

like image 923
mendez Avatar asked Jan 19 '23 01:01

mendez


1 Answers

Include this in your 'for' loop :

if (i % 5 == 4)
{
  codeArray[i] = '-';
} 
else 
{
    int index = random.Next(tokens.Length - 1);
    codeArray[i] = tokens[index];
}
like image 93
Michael Gehlke Avatar answered Jan 29 '23 20:01

Michael Gehlke