Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

textbox

I'm trying to save the contents of a textbox to a text file using Visual C#. I use the following code:

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);
            // close the stream
            tw.Close();
            MessageBox.Show("Saved to " + folderBrowserDialog3save.SelectedPath + "\\logfile.txt", "Saved Log File", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

but I only get the following line of text in the textfile:

System.Windows.Forms.TextBox, Text: 

Followed by only a short portion of what was actually in the textbox, ended with '...'. Why doesn't it write the entire contents of the textbox?

like image 263
muttley91 Avatar asked Jul 08 '10 20:07

muttley91


1 Answers

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.

like image 64
Ed Ropple Avatar answered Sep 19 '22 20:09

Ed Ropple