You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C# .NET6.0 WPF中如何从RichTextBox提取RTF字符串

WPF RichTextBox提取和加载RTF文本到变量的解决方案

提取RTF文本到字符串变量

WPF的RichTextBox没有直接的Rtf属性,但可以通过MemoryStream配合TextRange实现将RTF内容存入字符串变量,无需写入文件:

using System.IO;
using System.Windows.Documents;

// 假设你的RichTextBox实例名为richTextBox1
var textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd);
string rtfContent;

using (var memoryStream = new MemoryStream())
{
    textRange.Save(memoryStream, DataFormat.Rtf);
    memoryStream.Position = 0; // 重置流指针到起始位置
    using (var streamReader = new StreamReader(memoryStream))
    {
        rtfContent = streamReader.ReadToEnd();
    }
}

// 此时rtfContent即为包含所有格式的RTF字符串

将RTF字符串加载回RichTextBox

把保存的RTF字符串重新加载到RichTextBox,同样借助MemoryStream实现:

using System.IO;
using System.Windows.Documents;

// 假设要加载的RTF字符串为rtfContent
var textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd);

using (var memoryStream = new MemoryStream())
{
    using (var streamWriter = new StreamWriter(memoryStream))
    {
        streamWriter.Write(rtfContent);
        streamWriter.Flush();
        memoryStream.Position = 0;
        textRange.Load(memoryStream, DataFormat.Rtf);
    }
}

关键说明

  • MemoryStream是内存级数据流,无需创建物理文件,刚好满足将RTF内容转存到变量的需求。
  • 操作流后必须重置Position到0,否则读取或加载时会从流的末尾开始,导致内容为空。

内容的提问来源于stack exchange,提问作者Aquedus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 21:03:14