Visual C# – 将文本框的内容写入.txt文件
我正在尝试使用Visual C#将文本框的内容保存到文本文件中。 我使用以下代码:
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); } }
但我只在文本文件中获得以下文本行:
System.Windows.Forms.TextBox, Text:
接下来只是文本框中实际内容的一小部分,以“…”结尾。 为什么不写文本框的全部内容?
在这种情况下,使用TextWriter并不是必需的。
File.WriteAllText(filename, logfiletextbox.Text)
更简单。 您需要将TextWriter用于需要长时间保持打开状态的文件。
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); } }
小解释: tw.WriteLine
接受object
所以它不关心你传递什么。 在内部它调用.ToString
。 如果.ToString
未被覆盖, .ToString
返回类型的名称。 .Text
是TextBox
内容的属性
我想你需要的是:
tw.WriteLine(logfiletextbox.Text);
如果你不说’.Text’那就是你得到的
希望有所帮助!
选项:使用WriteLine()
,请注意保存到文件的内容是TextBox的文本以及换行符 。 因此,文件的内容将与TextBox的内容完全不匹配。 你什么时候关心这个? 如果您稍后使用该文件在文本框的Text属性中读回,并通过save-> load-> save-> load …
您选择保留所有文本(如果您using System.IO
):
文件。 WriteAllText (filename,textBox.Text)
文件。 WriteAllLines (filename, textBox。Lines )
如果你坚持使用TextWriter,你可以使用using
包装器处理Stream的处理,如果你需要在write方法中使用复杂的逻辑。
using( TextWriter tw = new ... ) { tw.Write( textBox.Text ); }
考虑到尝试访问文件以进行读取或写入时可能会抛出IOExceptions。 考虑捕获IOException并在应用程序中处理它(保留文本,向用户显示无法保存文本,建议选择不同的文件等)。