Update (2009-07-31): This bug is submitted to Microsoft Connect. You can follow the issue here.
The RichTextBox that is shipped with .NET Framework 3.5 SP1 contains a bug. This article shows a fix for the bug.
When converting plain text that contains a line break (\r), not to confuse with a new paragraph (\r\n), the RichTextFormat control displays the text correctly when loading plain text into the control. However, when the Rtf version of the plain text is loaded from the control, it is not exactly the same as represented by the control the first time. All line breaks (\r) are gone and the text is simply put onto one line.
The screenshot below shows the example application that reveals the bug.
Figure 1 – Screenshot with and without bug fix
How it is resolved
There are several available options how to resolve this problem. One of the options is to create a custom PlainTextToRtf converter. However, this is too much work, since you need to take care of everything then.
This is how I have resolved to issue. It's a workaround and only fixes the problem so you can keep using the RichTextBox control. However, I think Microsoft should fix this bug.
The helper methods used in the fix below are to improve the readability of the code. The example included in this package contains the implementation of these helper methods (CreateRichtTextBoxWithText, GetTextFromRichTextBox).
/// Converts plain text to Rtf with the bug fix.
/// Text to convert.
/// Rtf version of the text.
private string ConvertPlainTextToRtfWithFix(string text)
// Prepare some values
const string CarriageReturn = "\r";
const string LineFeed = "\n";
const string CarriageReturnLineFeed = "\r\n";
const string CustomCarriageReturn = "[cr]";
const string CustomLineFeed = "[lf]";
const string CustomCarriageReturnLineFeed = "[crlf]";
const string RtfCarriageReturn = "\\line ";
// Replace all known feeds to a custom constant
text = text.Replace(CarriageReturnLineFeed, CustomCarriageReturnLineFeed).Replace(CarriageReturn, CustomCarriageReturn).Replace(LineFeed, CustomLineFeed);
// Now convert all working feeds back
text = text.Replace(CustomCarriageReturnLineFeed, CarriageReturnLineFeed);
// Convert using a control
RichTextBox rtfControl = CreateRichTextBoxWithText(text);
// Read the text again (now it should be rtf)
text = GetTextFromRichTextBox(rtfControl);
// Now replace all known bugs
text = text.Replace(CustomCarriageReturn, RtfCarriageReturn);
// Return result
RichTextBox newline bug.zip (16.99 kb) [Downloads: 762]