将 richTextBox 内容保存到 c# 上的 .txt 文件

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。 C#。通常您必须注意手动使用正确的变体。

但 c# 有一个很好的解决方法,形式为 Environment.NewLine,它包含当前系统的正确变体。