Possible Duplicate:
Is this a good way to generate a string of random characters?
How can I generate random 8 character, alphanumeric strings in C#?
This is the code that I have so far.
private void button1_Click(object sender, EventArgs e)
{
string rand1 = RandomString(5);
string rand2 = RandomString(5);
string rand3 = RandomString(5);
string rand4 = RandomString(5);
string rand5 = RandomString(5);
textBox1.Text = rand1 + "-" + rand2 + "-" + rand3 + "-" + rand4 + "-" + rand5;
}
private static Random random = new Random((int)DateTime.Now.Ticks);
private string RandomString(int Size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < Size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
BUT it just creates a random string of 5 chars. I want it to create a string of 5 chars and integers. How would I do this? Thanks in advance!
replace
by
Note that your code doesn't create unpredictable random strings. In particular there are only 2 billion possible results, and if your computer gets restarted often, some of them are much more likely than others.
If you want unpredictable random strings, you should use RNGCryptoServiceProvider. You can fine an example at https://stackoverflow.com/a/1344255/445517 , you just need to add the hyphens.
Use an input array to draw your values from:
Or the (inevitable) Linq solution:
Copying from jon skeet's answer... https://stackoverflow.com/a/976674/67824