I tried to generate 4 random numbers with 4 digits into a text file, but the only thing i can type to it is just text in the quotes. Also you need to type an address to a textbox, but that doesn't matter. How can i type several ints into that file? Here's how i tried to do that.
private void btnGenerate_Click(object sender, EventArgs e)
{
int i;
i = textboxMAIL.Text.Length;
if (i < 1)
{
MessageBox.Show("No address!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Successfully saved into psc.txt.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
Random r;
r = new Random();
int generate;
generate = r.Next(9999);
Random r2;
r2 = new Random();
int generate2;
generate2 = r2.Next(9999);
Random r3;
r3 = new Random();
int generate3;
generate3 = r3.Next(9999);
Random r4;
r4 = new Random();
int generate4;
generate4 = r4.Next(9999);
if (!File.Exists("c://desktop//psc.txt")) // If file does not exists
{
File.Create("c://desktop//psc.txt").Close(); // Create file
using (StreamWriter sw = File.AppendText("c://desktop//psc.txt"))
{
sw.WriteLine(generate, generate2, generate3, generate4); // Write text to .txt file
}
}
else // If file already exists
{
File.WriteAllText("c://desktop//psc.txt", String.Empty); // Clear file
using (StreamWriter sw = File.AppendText("c://desktop//psc.txt"))
{
sw.WriteLine(generate, generate2, generate3, generate4); // Write text to .txt file
}
}
}
}
Check the documentation for StreamWriter.WriteLine
. You're passing it 4 int
values, but there is no version of that method which expects that. The first parameter of that method is the string to write.
If you want to write each value on its own line, convert each to a string and pass that to the method:
sw.WriteLine(generate.ToString());
sw.WriteLine(generate2.ToString());
sw.WriteLine(generate3.ToString());
sw.WriteLine(generate4.ToString());
If you want them to all be concatenated to the same line, the first argument is the string with format placeholders and the remaining arguments are the values for the placeholders:
sw.WriteLine("{0}{1}{2}{3}", generate, generate2, generate3, generate4);
Or with more modern syntax, if you're using a more recent C# version:
sw.WriteLine($"{generate}{generate2}{generate3}{generate4}");
It's also worth noting that your random number generation is broken. The code you have is very likely going to produce 4 identical random numbers every time. Refer to this question for more information. In short, you should use one instance of Random
and use it to generate all of the numbers you need.