2011-04-12 28 views
6

¿Hay una manera fácil de extraer texto de una cadena Rtf sin usar RichTextBox?Cómo convertir una cadena rtf a texto en C#

Ejemplo:

{\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} 
} 
} 

debería volver:

foo 
bar 
+1

¿Usted realmente quiere decir "sin usar RichTextBox" o qué lugar quiere decir "sin mostrando un RichTextBox "? – Heinzi

+1

sin usar RichTextBox. esto será en un dll cargado por un servidor de informes. Y el dll devuelve un error si incluye windows.forms – dcarneiro

Respuesta

2

Hay un simple artículo en MSDN para lograr lo que quiere: 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

Quiero evitar hacer referencia a System.Windows.Forms.dll – dcarneiro

+0

Esto utiliza un RichTextBox que OP dijo que quería evitar. Aunque estoy de acuerdo, la mejor manera de hacerlo sería simplemente no mostrar el RTB. – SeeSharp

Cuestiones relacionadas