-1

im creating a program similar to Notepad++ but I have run in to a problem, when I save a file it puts all text in one line, like this:

Test Line 1Test Line 2Test Line 3

Instead of:

Test Line 1

Test Line 2

Test Line 3

Here is the code I use to save:

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    String filename = saveFileDialog1.FileName;
    if (filename != "")
    {
        File.WriteAllText(filename, "");
        StreamWriter strw = new StreamWriter(filename);
        strw.Write(richTextBox1.Text);
        strw.Close();
        strw.Dispose();
    }
}

There probably is a super easy solution to this, but I'm quite new to C# and can't figure it out. Any help is appreciated!

Community
  • 1
  • 1
MoDz Trolls
  • 37
  • 2
  • 5
  • 1
    You have told us what the output looks like, but what is the input? – maccettura Feb 28 '18 at 20:55
  • 2
    What makes you think it is just a single line? Did you try opening it in multiple text editors (e.g. Notepad and Notepad++)? Please update your post with the value of `richTextBox1.Text and `richTextBox1.Rtf`. – mjwills Feb 28 '18 at 20:55
  • if you first build a "stringbuilder" and then you write in your file all content of your stringbuilder, it can working!! – Martin Chinome Feb 28 '18 at 20:57
  • 1
    Curious why you didn't just do `File.WriteAllText(filename, richTextBox1.Text);` – Jim W Feb 28 '18 at 21:03
  • 3
    RichTextbox is oddball, its Text property uses \n line-ending instead of \r\n. Consider the dedicated RichTextbox.SaveFile() method. – Hans Passant Feb 28 '18 at 21:21
  • @HansPassant Actually, it seems more things in the .Net framework do. I recently discovered that message boxes also assume the text to show uses `\n` as line breaks; using Ctrl+C to copy the contents of a shown MessageBox will result in text which has all occurrences of `\n` replaced by `Environment.NewLine`. If you use `\r\n` line breaks in it, on windows, you end up with `\r\r\n` everywhere. – Nyerguds Mar 07 '18 at 12:15

2 Answers2

4

Rich textbox uses only line feed, if you need them both you can add during save:

File.WriteAllText(filename, richTextBox1.Text.Replace("\n","\r\n");
owairc
  • 1,890
  • 1
  • 10
  • 9
2

A really simple workaround:

File.WriteAllLines(filename, richTextBox1.Lines);
Nyerguds
  • 5,360
  • 1
  • 31
  • 63