2011-04-12 67 views
6

有沒有簡單的方法從Rtf字符串中提取文本而不使用RichTextBox如何將rtf字符串轉換爲C#中的文本

例子:

{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Segoe UI;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\f2 {\lang2070\ltrch foo}\li0\ri0\sa0\sb0\fi0\ql\par} 
{\f2 {\lang2070\ltrch bar }\li0\ri0\sa0\sb0\fi0\ql\par} 
} 
} 

應該返回:

foo 
bar 
+1

你真的意味着「不使用RichTextBox的」還是你的意思,而「不CodeProject上的樣本顯示一個RichTextBox「?不使用RichTextBox的 – Heinzi 2011-04-12 11:44:58

+1

。這將在一個由報告服務器加載的dll上。如果它包含windows.forms – dcarneiro 2011-04-12 11:46:54

回答

2

有MSDN上的一個簡單的文章,以達到你想要的東西:http://msdn.microsoft.com/en-us/library/cc488002.aspx

class ConvertFromRTF 
{ 
    static void Main() 
    { 

     string path = @"test.rtf"; 

     //Create the RichTextBox. (Requires a reference to System.Windows.Forms.dll.) 
     System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox(); 

     // Get the contents of the RTF file. Note that when it is 
     // stored in the string, it is encoded as UTF-16. 
     string s = System.IO.File.ReadAllText(path); 

     // Display the RTF text. 
     System.Windows.Forms.MessageBox.Show(s); 

     // Convert the RTF to plain text. 
     rtBox.Rtf = s; 
     string plainText = rtBox.Text; 

     // Display plain text output in MessageBox because console 
     // cannot display Greek letters. 
     System.Windows.Forms.MessageBox.Show(plainText); 

     // Output plain text to file, encoded as UTF-8. 
     System.IO.File.WriteAllText(@"output.txt", plainText); 
    } 
} 
+5

dll會返回一個錯誤我想避免引用System.Windows.Forms.dll – dcarneiro 2011-04-12 11:48:15

+0

這使用了一個RichTextBox,OP說他想避免。雖然我同意這樣做的最佳方式是僅僅不顯示RTB。 – SeeSharp 2011-04-12 11:48:34

相關問題