在C# .Net6.0 WPF中从RichTextBox中提取RTF字符串

问题描述 投票:0回答:1

我正在努力从 RichTextBox 中获取 RTF 文本。我正在使用 C# .Net6.0、WPF。

我需要从 RichTextBox 获取 RTF 字符串并将其存储在变量中。该变量位于生成 RTF 字符串所在文件的类中。

RTF 字符串应包含所有格式,如粗体、斜体和彩色文本。当变量加载回 RichTextBox 时,它应该显示保存时的所有格式。

我知道如何提取纯文本,但不知道如何提取 RTF 文本。 RichTextBox.Rtf 仅在 WinForms 中可用。在互联网上搜索只让我找到“如何从 RichTextBox 获取纯文本”,但似乎没有其他人遇到我遇到的这个问题。

保存 RTF-String 的变量是一个字符串。 微软官方文档也没有帮助。

我尝试寻找一种方法来显示 RichTextBox 中的 RTF 字符串。我还在 TextRange 中搜索,从 RichTextBox 中获取纯文本,但 TextRange 似乎只显示纯文本。我发现了 TextRange.Save(stream, DataFormat.RTF) 之类的东西,但这将字符串直接保存到文件而不是变量中。

c# wpf .net-6.0 richtextbox rtf
1个回答
0
投票

要获取RTF格式的

FlowDocument
内容,您可以使用以下扩展方法:

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

public static class FlowDocumentExt
{
    public static string RawRtf(this FlowDocument document)
    {
        // Select all the document content
        var range = new TextRange(document.ContentStart, document.ContentEnd);

        // Save to a MemoryStream
        range.Save(stream, DataFormats.Rtf);

        // Convert from stream to the string 
        return Encoding.ASCII.GetString(stream.ToArray());
    }
}

如何调用它的示例(

rtb
RichTextBox
的名称):

string rtf = rtb.Document.RawRtf();

测试截图:

© www.soinside.com 2019 - 2024. All rights reserved.