65.9K
CodeProject is changing. Read more.
Home

Saving and Restoring RichTextBox Formatted Text. Alternate to SaveFile/LoadFile

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.20/5 (8 votes)

Feb 2, 2006

CPOL

1 min read

viewsIcon

81662

Overcoming the RichTextBox.LoadFile 'Invalid file format' error on non PlainText.

Introduction

I have spent some hours searching the web trying to figure out why the RichTextBox LoadFile method fails on anything but PlainText when the System.IO.Stream data parameter is a MemoryStream. On browsing most of the web hits, I didn't find a solution and all of the references to richTextBox1.LoadFile(memoryStream, ...) conveniently used RichTextBoxStreamType.PlainText, which of course works.

Failure

The following code is a simple example highlighting the problem. I am simply attempting to transfer the contents of one RichTextBox to another retaining the text format properties.

void Test1() {
MemoryStream ms = new MemoryStream();
// retain formatting - no embedded ole objects
this.richTextBox1.SaveFile(ms, RichTextBoxStreamType.RichNoOleObjs);
// re-position the stream
ms.Position = 0;
// the following line throws an exception 'Invalid file format'
this.richTextBox2.LoadFile(ms, RichTextBoxStreamType.RichNoOleObjs);
}

Success

After some considerable curses directed both at my computer and my dog, I examined the other RichTextBox properties and success (was embarrassingly simple):

void Test2() {
string rtfText = this.richTextBox1.Rtf;
// process formatted RTF text - i.e. save to database etc.
// ...
// reload formatted RTF text
this.richTextBox2.Rtf = rtfText;
}

For my purpose, I wanted to expand coded entries to full text descriptions. However, if the formatted text is to be saved to a database, as I will be doing once the edit (and my current coding) is completed, then I will simply say:

dataRow["FormattedText"] = this.richTextBox1.Rtf;

The database column type can be Text or varchar/nvarchar, no BLOB required. Works similarly for XML.

Conclusion

My requirement does not include storing images in the RichTextBox so I have not tested the same. None of the articles I found on my web search made a reference to using the RTF property value as an alternative to SaveFile/LoadFile. It seems that for many situations (e.g. editing/viewing the result in Notepad, database / XML store) saving the RTF property could provide a more flexible solution.

History

  • 2nd February, 2006: Initial post