problem with richTextBox

T

Tony Johansson

Hello!

I have this eventhandler method OpenToolStripMenuItem_Click shown below.
When statement richTextBox.Rtf = contents;
is executed I get following error message "Can't read fileFile format is not
valid" from the catch handler.
The file that I open by using openFileDialog has filename test.txt and
contains this text "This is a test by me."

Can somebody explain why I get this kind of error message ?

private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
Stream streamInp = openFileDialog.OpenFile(); //Open the specified
file
if (streamInp != null)
{
//If the file was successfully opened get a StreamReader
StreamReader streamRdr = new StreamReader(streamInp);

//Read the entire file into the richTextBox
string contents = streamRdr.ReadToEnd();
richTextBox.Rtf = contents;
streamRdr.Close();
}
}
}
catch (Exception ex)
{
richTextBox.Text = "Can't read file";
richTextBox.Text += ex.Message;
}
}


//Tony
 
M

Morten Wennevik [C# MVP]

Hi Tony,

The error message is misleading as it has nothing to do with the actual
reading of the file. As Peter pointed out the content of the file is not rtf
formatted, and setting anything in a RichTextBox.Rtf property needs to
include the rtf codes. Even unformatted text has rtf codes describing font
type and size. Either set the Text property or manually assemble the Rtf
yourself.

The minimum of information you need to provide is an rtf flag, the
RichTextBox will then add the remaining rtf codes. One could argue that it
could just add the rtf flag too if it wasn't provided, but it does not.

richTextBox1.Rtf = "{\\rtf1" + contents + "}";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top