AaronLikesKek AaronLikesKek - 2 months ago 14
C# Question

Formatted string in File.WriteAllText and File.Create

private void panel1_Click(object sender, EventArgs e)
{
var fileStream = File.Create(@"C:\Program Files\CopTablet\Report{0}.txt", textBox1);
fileStream.Close();
}


So with this, I'm trying to basically make a text file everytime the panel(used as button) is clicked with the name
Report{0}
but obviously that doesn't work.
The {0} would stand for
textBox1.Text
and that textbox basically contains a random number. So the end file would be called
Report(RandomNumber).txt


And after that I want to write a var to it which I already have.
but again I'm not too sure how to do this.
I had something likes this but didn't work:
File.WriteAllText(string.Format(@"C:\Program Files\CopTablet\Report{0}.txt", textBox1.Text, comb));

The {0} directs to textBox1.Text again so you write in the file I just made and then the "comb" is the var that I want to write in the text file.

Answer

Either use String.Format like:

String.Format(@"path\Report{0}.txt", textBox1.Text)

Or string interpolation like:

$@"path\Report{textBox1.Test}.txt"