-1

I would like to create the txt file that has name from my textbox1 and at the same time, I would like to write in it text from my textbox2.

Can you help me?

I have tried this

private void button1_Click(object sender, EventArgs e)
{
    string path = @"C:\Users\felc\Desktop\file\" + textBox1.Text + 
     ".txt";

    File.Create(path);

    using (var tw = new StreamWriter(path, true))
    {
        tw.WriteLine(textBox1.Text);
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

2 Answers2

0

I would suggest you first check if the file already exists, and only create it if not. Something like:

private void button1_Click(object sender, EventArgs e)
{

    string path = @"C:\Users\felc\Desktop\file\" + textBox1.Text + ".txt";

    if (!File.Exists(path))
    {
        File.Create(path);
    }

    using(var tw = new StreamWriter(path, false))
    {
        tw.WriteLine(textBox2.Text);
    }
}

Note : in case you would like your code to append line to the file and not to re-write it, change the secont argument to "true": new StreamWriter(path, true)

Note 2 : You wrote the value of the first text box to the file instead of the second one. hence, in your code the text in the file will be the same as it's name.

AvrahamL
  • 181
  • 4
  • 16
0
 using(var tw = new StreamWriter(path, false))
{
    tw.WriteLine(textBox2.Text);
}
  • 1
    Thanks for answering a question - can you add some explanation to help OP understand what it is about your answer that solves the problem. It also makes the site more useful for people (of various levels of experience) who might come across the question later. – Joe Mayo Apr 19 '20 at 01:12