换行符\r\n (CR/LF) 是RichTextBox 控件中文本格式的一部分。转换为文本时的每个段落都将附加\r\n。
这意味着当用户按下 ENTER 按钮时,带有\r\n 的新段落将添加到RichTextBox 控件中。当使用 Microsoft 文档中描述的 StringFromRichTextBox() 方法从 RichTextBox 中提取文本内容时,它将返回一个字符串,其中所有段落都由 \r\n 分隔。
上面关于cmets的解释:
一个换行符 (\r\n) 被添加到文件的后面,除非用户明确添加这个换行符,否则我不想要它。
换行符\r\n 仅作为每个段落结尾的一部分添加到文件末尾。
注意:如果需要保存并随后加载保存的文档,可以使用TextRange.Save() 和TextRange.Load() 方法:
public void SaveRtf(RichTextBox rtb, string file)
{
var range = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
using (var stream = new StreamWriter(file))
{
range.Load(stream.BaseStream, DataFormats.Rtf);
}
}
public void LoadRtf(RichTextBox rtb, string file)
{
var range = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
using (var stream = new StreamWriter(file))
{
range.Save(stream.BaseStream, DataFormats.Rtf);
}
}
如果要保存整个RuchTextBox 内容,则将使用new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text,而不是恢复后的任何文本格式都将丢失。