10
Reply

Getting richtextbox to load .txt files and .rtf files

Kevin Cope

Kevin Cope

Feb 1 2011 5:14 PM
7.4k
So I'm Currently working on a tabbed notepad using a richtextbox and i've come across a problem.
I want it to be able to open .txt files and .rtf.

The code i'm using to load the file is

 GetRichTextBox().LoadFile(openFile1.FileName);

Meaning it's going to assume it's going to open a .rtf file or something of supported format.
Though if I try to open a .txt file it crashes and tells me my formats not right. 
Though if I use:
 GetRichTextBox().LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);
And then try to load up a .rtf file I get something like

"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}}
{\*\generator Msftedit 5.41.15.1515;}\viewkind4\uc1\pard\f0\fs20 So how the hell\par
Do \par
I fix this\par
Problem\par
}
"

So here is my question.
How can I load both .txt files and .rtf files into my richtextbox
(Heres the full code i'm using)

 
            OpenFileDialog openFile1 = new OpenFileDialog();

           
            openFile1.DefaultExt = "*.rtf";
            openFile1.Filter = "RTF Files|*.rtf|Text Documents|*.txt|All Files|*.*";

           
            if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
               openFile1.FileName.Length > 0)
            {
                

                GetRichTextBox().LoadFile(openFile1.FileName);


Any suggestions?

Answers (10)