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

后端 未结 5 1805
遇见更好的自我
遇见更好的自我 2020-12-31 11:28

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         


        
5条回答
  •  生来不讨喜
    2020-12-31 11:53

    Options: When using WriteLine(), note that the content saved to the file is the Text of the TextBox, plus a newline. So, the contents of the file will not match exactly the contents of the TextBox. When would you care about this? If you use the file to read back in a Text property of a text box later, and go through the save->load->save->load...

    Your choices to preserve all text (if you using System.IO):

    File.WriteAllText( filename, textBox.Text )

    File.WriteAllLines( filename, textBox.Lines )

    If you insist on using TextWriter, you could use the using wrapper to handle disposing of the Stream, if you need to use complex logic in your write method.

    using( TextWriter tw = new ... )
    {
        tw.Write( textBox.Text );
    }
    

    Consider that IOExceptions may be thrown whenever attempting to access a file for reading or writing. Consider catching an IOException and handling it in your application (keeping the text, displaying to the user that the text could not be saved, suggest choosing a different file, etc).

提交回复
热议问题