【发布时间】:2018-05-06 17:59:35
【问题描述】:
我的数据库中有一个包含 RTF 格式文本的列。
如何使用 C# 仅获取它的纯文本?
谢谢:D
【问题讨论】:
-
Here's another question 讨论正则表达式的方式。
我的数据库中有一个包含 RTF 格式文本的列。
如何使用 C# 仅获取它的纯文本?
谢谢:D
【问题讨论】:
Microsoft 提供 an example,他们基本上将 rtf 文本粘贴在 RichTextBox 中,然后读取 .Text 属性...感觉有点笨拙,但它确实有效。
static public string ConvertToText(string rtf)
{
using(RichTextBox rtb = new RichTextBox())
{
rtb.Rtf = rtf;
return rtb.Text;
}
}
【讨论】:
RichTextBox rtb 立即超出范围,它似乎也会添加到用户对象计数中并且永远不会减少。因此我认为最好将其包装在 using 语句中。
对于 WPF,您可以使用 (使用 Xceed WPF Toolkit)这个扩展方法:
public static string RTFToPlainText(this string s)
{
// for information : default Xceed.Wpf.Toolkit.RichTextBox formatter is RtfFormatter
Xceed.Wpf.Toolkit.RichTextBox rtBox = new Xceed.Wpf.Toolkit.RichTextBox(new System.Windows.Documents.FlowDocument());
rtBox.Text = s;
rtBox.TextFormatter = new Xceed.Wpf.Toolkit.PlainTextFormatter();
return rtBox.Text;
}
【讨论】:
如果你想要一个纯代码版本,你可以自己解析 rtf,只保留文本位。这是一些工作,但不是很困难的工作 - RTF 文件的语法非常简单。 Read about it in the RTF spec.
【讨论】: