C# populate RichTextBox with stream -- File Format is not Valid

2k views Asked by At

How do I load .rtf data from a stream into a RichTextBox?

I am trying to put an .rtf stream into a RichTextBox using this code:

using (Stream s = GenerateStreamFromString(rtfString))
{
    rtbDisplay.LoadFile(s, RichTextBoxStreamType.RichText);
    renderer.Render(document, "C:\\Users\\fairskunk\\Desktop\\test.rtf", null);
}

The last line creates an .rtf file using MigraDoc and saves it. I can open that file in a conventional editor just fine.

The first line doesn't work -- I get a "File Format is Not Valid" error when I try to load data into the RichTextBox from a stream instead of a file.

An unhandled exception of type 'System.ArgumentException' occurred in >System.Windows.Forms.dll

Additional information: File format is not valid.

When the program first executes I load a previously-exported (via the last line above) .rtf file directly into the RichTextBox, which displays just fine:

rtbDisplay.LoadFile("C:\\Users\\fairskunk\\Desktop\\test.rtf",
    RichTextBoxStreamType.RichText);

The .rtf stream should be good because it can be exported to a file that conventional editors can read. Why can't I put the stream into the RichTextBox?

Edit -- problem solved

I was using the MigraDoc RtfDocumentRenderer.RenderToString() command incorrectly, in code that I hadn't inserted above.

RenderToString takes two arguments; the document to be rendered and a string for the working directory ('null' seems to work). It returns a string for the rendered document.

I thought the string in the argument received the rendered document. RenderToString did render the document but the resulting string was not assigned to anything.

Corrected code:

string rtfString = "";
MemoryStream stream = new MemoryStream();
RtfDocumentRenderer renderer = new RtfDocumentRenderer();
rtfString = renderer.RenderToString(document, null);

using (Stream s = GenerateStreamFromString(rtfString))
{
    rtbDisplay.LoadFile(s, RichTextBoxStreamType.RichText);
    //renderer.Render(document, "C:\\Users\\fairskunk\\Desktop\\test.rtf", null);
}
0

There are 0 answers