Search code examples
c#winformsrtfstreamwriter

How to write several RichTextBox Contents into one RTF file preserving font formats of each RichTextBox


I have a Winforms project where I can write text into a RichTextBox, and some controls to set the font formats of the written text. I am able to save and append text to RTF file, but I'm having a problem of preserving font formats of each RichTextBox. Any Help?

CODE:

RichTextBox r1 = new RichTextBox();
RichTextBox r2 = new RichTextBox();
string nickName = "Test: ";
string message = "Hi this is a test message";
r1.Text = nickName;
r1.ForeColor = Color.Blue;

r2.Text = message;
r2.ForeColor = Color.Black;

string path = @"d:\Test.rtf";
if (!File.Exists(path))
{
    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
    using (StreamWriter sw = new StreamWriter(fs))
    {
        sw.WriteLine(r1.Rtf);
        sw.WriteLine(r2.Rtf);
        sw.Close();
    }
}
else
{
    using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
    using (StreamWriter sw = new StreamWriter(fs))
    {
        sw.WriteLine(r1.Rtf);
        sw.WriteLine(r2.Rtf);
        sw.Close();
    }
}

Solution

  • You can avoid this problem by merging all the content into the same RichTextBox. Sample:

    r1.Text = r1.Text + Environment.NewLine;
    r1.SelectAll();
    r1.Copy();
    r2.Paste();
    
    r2.SaveFile(path);
    

    This approach works fine with StreamWriter as you were using it. On the other hand, why not using a simpler/specifically-designed-for-this-purpose method (SaveFile)? If you don't want to replace the contents in r2, you can just rely on a temporary RichTextBox:

     r1.Text = r1.Text + Environment.NewLine;
     r1.SelectAll();
     r1.Copy();
     RichTextBox temp = new RichTextBox();
     temp.Paste();
     r2.SelectAll();
     r2.Copy();
     temp.Paste();
    
     temp.SaveFile(path);
    

    NOTE: there might be problems when using StreamWriter (to append, for example). Bear in mind that RTF is a special format which requires a special treatment: perform any modification from the RichTextBox control (add, remove, edit, etc. text/format) and rely on the methods LoadFile and SaveFile, rather than in the ones for TXT files (i.e., StreamReader/StreamWriter).