[英]Save richTextBox content to .txt file on c#
当你编写这段代码时:
string path = @"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string[] createText = { "Hello", "And", "Welcome" };
File.WriteAllLines(path, createText);
}
现在我想将每行richTextBox内容保存到.txt文件的新行,如结果图像。 我写下我的代码如下:
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.AppendText(textBox1.Text +"\n");
System.IO.File.WriteAllText(@"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt", richTextBox1.Text + Environment.NewLine);
}
但是,结果是
由于某种原因,RichTextBox控件包含换行符的“\\ n”而不是“\\ r \\ n”。
尝试这个:
System.IO.File.WriteAllText(
@"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt",
richTextBox1.Text.Replace("\n", Environment.NewLine));
更好的方法是使用richTextBox1.Lines
,它是一个包含所有行的字符串数组:
System.IO.File.WriteAllLines(
@"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt",
richTextBox1.Lines);
为了完整起见,这是另一种方式:
richTextBox1.SaveFile(@"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt",
RichTextBoxStreamType.PlainText); //This will remove any formatting
问题是文本输入和文本文件所需输入之间的转换。 可能性如下:
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.AppendText(textBox1.Text);
System.IO.File.WriteAllText(@"C:\Users\Mohammad_Taghi\Desktop\ab\a.txt", richTextBox1.Text.Replace("\n", Environment.NewLine));
}
问题不仅在于文本框特定,而且还可能是特定于操作系统的(例如,如果您读取在Linux系统上创建的文件,....)。 有些系统只使用\\ n作为新行\\ r \\ n \\ n \\ n \\ n \\ n \\ n \\ n C#。 通常,您必须手动使用正确的变体。
但是c#在Environment.NewLine的形式有一个很好的解决方法,它包含当前系统的正确变体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.