Search code examples
c#.netsavefiledialog

Saving contents of rich textbox to file, perserving multilines


Ok so I'm trying to make a simple text editing program and I got the files to save, but the problem is that all line breaks are removed in the saved file

ie

text as it appears in the text editor

123
456
789

text as it appears in the saved file

123456789

code I'm using
string filename = saveFileDialog1.FileName; File.WriteAllText(filename,richTextBox1.Text);
and
string filename = saveFileDialog1.FileName;
File.AppendAllText(filename, richTextBox1.Text);

These both produce the same result ie no linebreaks

Any ideas on what I'm doing wrong?


Solution

  • You should just be able to use File.WriteAllLines with the RichTextBox.Lines property, as File.WriteAllText and File.AppendAllText is going to ignore you line formatting.

    Example

    string filename = saveFileDialog1.FileName;
    File.WriteAllLines(filename, richTextBox1.Lines);