2012-05-01 106 views
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) 

任何帮助,为什么发生这种情况或我们如何解决它,将不胜感激。

编辑:感谢杰里米的解释,我对RTF转换替代方案的建议。

+0

我不认为你应该使用来自服务的窗口控件(来自'System.Windows.Forms'的任何东西)。它甚至可能在一个壁橱里的无头盒子上运行。 – Thomas

+0

谢谢托马斯,是的,我知道这一点,任何建议为富文本转换的可靠替代? –

回答

2

最后我用这个。我知道它可能不会解析RTF文本的100%,但是我们会将其与我们的实时数据进行比对来测试它,并且它对我们的目的来说工作正常。

Regex.Replace(rtfString, @"\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?", ""); 
3

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

在服务中使用UI库通常不是一个好主意,因为如果没有用户是不能保证这些库是可访问的登录。

我会找到不同的方式来去除RTF格式

+0

谢谢杰里米,我正在尝试寻找转换的替代方案。 –

相关问题