Sivabalakrishnan
Sivabalakrishnan

Reputation: 515

How to open and read the content of ".RTF" File using c#

My need : I need to open an RTF File and read the content inside the RTF File and store it in a string variable.

What i have done : I have done it using "microsoft.office.interop.word.dll" ie.. Docment.open(String Filename);

But My Final necessity is : I need to open it using some other way to read the RTF File. This is Because in AzureFunction (microsoft.office.interop.word.dll is not supported ) ie.. word cant be installed in server.

OpenXML - This is used to open word , excel , powerpoint files . it cannot able to open RTF File.

Any possible answer is welcomed.

Upvotes: 0

Views: 6630

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109852

If you want to convert an RTF file to plain text, keeping only the text and losing all formatting and other non-text elements such as bitmaps, it is possible by using System.Windows.Forms.RichTextBox.

Note that you do not need an application with a user interface to do this; you can use RichTextBox in, for example, a service - but you will need to reference System.Windows.Forms.dll in order to do so.

The code to convert from an RTF file to a plain text string would look like this:

using System.Windows.Forms;

public static string RtfFileAsPlainText(string rtfPathName)
{
    using (var rtf = new RichTextBox())
    {
        rtf.Rtf = File.ReadAllText(rtfPathName);
        return rtf.Text;
    }
}

Upvotes: 4

Related Questions