从富文本格式转换为纯文本的问题

4

我们目前有一个应用程序(Windows服务),它连接到另一个我们的应用程序并获取发票。在发票中,有一个RTF字段用于页眉/页脚字段。当我们获取数据时,使用以下代码将RTF转换为纯文本:

public static string ConvertFromRTFToPlainText(string rtfString)
{
    if (rtfString == null)
        return null; 

    System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox();

    if (rtfString.StartsWith("{\\rtf1"))
        rtBox.Rtf = rtfString;
    else
        rtBox.Text = rtfString;

    return rtBox.Text;
}

这在大部分情况下都有效,但有些情况下(尤其是一个特定的客户端每次都会发生)我会遇到这个异常:

Exception Message:Error creating window handle.
Stack trace:
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.TextBoxBase.CreateHandle()
at System.Windows.Forms.RichTextBox.set_Rtf(String value)
at SmartTrade.Common.API.Tools.RTFHelperUtility.ConvertFromRTFToPlainText(String rtfString)
at SmartTrade.Desktop.Proxy.API.ObjectMapper.InvoiceObjectMapper.CovertToAPIInvoice(Invoice domainInvoice)

任何有关这种情况发生原因或我们如何解决它的帮助都将不胜感激。编辑:感谢Jeremy的解释,我正在寻求RTF转换替代方案的建议。

我认为你不应该从服务中使用窗口控件(任何来自System.Windows.Forms的控件)。它甚至可能在某个壁橱里运行在一个没有显示器的盒子上。 - Thomas
谢谢Thomas,是的,我知道这个问题,你有没有可靠的替代方案来进行富文本转换? - Toby Holland
2个回答

3

我认为这可能是在没有安装UI库的终端类型机器上抛出的?或者可能是没有加载它们(即如果没有用户登录)

通常不建议在服务中使用UI库,因为不能保证在没有用户登录的情况下可以访问这些库。

我会找到一种不同的方法来删除RTF格式


谢谢Jeremy,我正在尝试寻找一种转换的替代方案。 - Toby Holland

3
我最终使用了这个。我知道它可能无法完全解析RTF文本,但我们对其进行了实际数据测试,对于我们的目的来说它可以正常工作。
Regex.Replace(rtfString, @"\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?", "");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接