Visual C# - Write contents of a textbox to a .txt file

Using the TextWriter isn't really necessary in this case.

File.WriteAllText(filename, logfiletextbox.Text) 

is simpler. You'd use TextWriter for a file you need to keep open for a longer period of time.


private void savelog_Click(object sender, EventArgs e)
    {
        if (folderBrowserDialog3save.ShowDialog() == DialogResult.OK)
        {
            // create a writer and open the file
            TextWriter tw = new StreamWriter(folderBrowserDialog3save.SelectedPath + "logfile1.txt");
            // write a line of text to the file
            tw.WriteLine(logfiletextbox.Text);
            // close the stream
            tw.Close();
            MessageBox.Show("Saved to " + folderBrowserDialog3save.SelectedPath + "\\logfile.txt", "Saved Log File", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

small explanation: tw.WriteLine accepts object so it doesn't care what do you pass. Internally it calls .ToString. If .ToString is not overriden it just returns type's name. .Text is property with contents of TextBox


I think what you need is:

tw.WriteLine(logfiletextbox.Text);

if you don't say '.Text' that's what you get

Hope that helps!

Tags:

C#

Textbox