在 C# 中从 RichTextBox 中提取 RTF 字符串。Net6.0 WPF [已关闭]

Extract RTF String from RichTextBox in C# .Net6.0 WPF [closed]

提问人:Aquedus 提问时间:9/25/2023 更新时间:9/25/2023 访问量:135

问:


想改进这个问题吗?更新问题,使其仅通过编辑这篇文章来关注一个问题。

上个月关闭。

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

我需要从 RichTextBox 获取 RTF 字符串并将其存储在变量中。此变量位于生成 RTF 字符串应位于的 File 的类中。

RTF-String 应包含所有格式,如粗体、斜体和彩色文本。当 Variable 重新加载到 RichTextBox 中时,它应显示所有格式,就像保存时一样。

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

应保存 RTF-String 的变量是字符串。 官方的 Microsoft 文档也没有帮助。

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

C# WPF Net-6.0 RichTextBox RTF

评论

1赞 Rand Random 9/25/2023
I found something as TextRange.Save(stream, DataFormat.RTF) but this saved the string directly to a file instead of a variable.- 为什么不使用 MemoryStream?

答:

0赞 Jackdaw 9/25/2023 #1

若要获取 RTF 格式的内容,可以使用以下扩展方法:FlowDocument

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

public static string RawRtf(this FlowDocument document)
{
    using (var stream = new MemoryStream())
    {
        // 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());
    }
}

如何调用它的示例(是 的名称):rtbRichTextBox

string rtf = rtb.Document.RawRtf();

测试截图:

enter image description here

评论

0赞 Jackdaw 9/27/2023
@Aquedus:根据内容的不同,可以使用 Encoding.UTF8Encoding.Unicode 属性来获取所需的字符串格式。RichTextBox