1
private void btnDump_Click(object sender, EventArgs e)
{
    using (StreamWriter sw = new StreamWriter("E:\\TestFile.txt"))
    {
        // Add some text to the file.
        sw.WriteLine(txtChange.Text);
    }
}

This dumps the text of txtChange to a text file. txtChange is a Rich text box and has line breaks (new lines) in it.

When the user clicks the Dump button all the text is Dumped but not on new lines.

E.g. txtChange looks like

1
2
3
4

dumping the text looks like 1234

How do i format the dumping of the text so that the text is on new lines?

Dan1676
  • 1,685
  • 8
  • 24
  • 35

5 Answers5

10

You should use the Lines property instead:

File.WriteAllLines(@"E:\TestFile.txt", txtChange.Lines);

You don't really need to use a stream since the File class contains these static convenience methods - short and to the point.

Above will replace any existing content with the text lines contained in your text box txtChange. If you want to append content use the appropriately named File.AppendAllLines() instead.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • @hungryMind: That sound logical to me, too, but looking at `WriteLine` in reflector I don't think it's doing any line collapsing. – sorpigal Nov 30 '11 at 14:09
  • @BrokenGlass This works fine, I have just tried adding another text box contents but this overwrites the text taken from txtChange, Do you know the command to add text ('copying' over the new lines as well)? – Dan1676 Nov 30 '11 at 14:13
  • @Dan1676: Added to my answer - check out the `File` class on msdn for more convenience methods. – BrokenGlass Nov 30 '11 at 17:03
4

just add a newline char:

private void btnDump_Click(object sender, EventArgs e)
{
    using (StreamWriter sw = new StreamWriter("E:\\TestFile.txt"))
    {
        // Add some text to the file.
        sw.WriteLine(txtChange.Text + "\r\n");
    }
}
hcb
  • 8,147
  • 1
  • 18
  • 17
1

If it contains \r's as you mentioned, you should try this

using (StreamWriter sw = new StreamWriter("E:\\TestFile.txt"))
{
    // Add some text to the file.
    sw.WriteLine(txtChange.Text.Replace("\r", "\r\n");
}
Shai
  • 25,159
  • 9
  • 44
  • 67
0

You can also do:

private void btnDump_Click(object sender, EventArgs e)
 {
     using (StreamWriter sw = new StreamWriter("E:\\TestFile.txt"))
     {
         // Add some text to the file.
         sw.WriteLine(txtChange.Text + Environment.NewLine);
     }
 } 
Andrey Marchuk
  • 13,301
  • 2
  • 36
  • 52
0

Take a look at Replace Line Breaks in a String C# and replace all linebreaks so it matches Windows Standard.

take a look at http://en.wikipedia.org/wiki/Newline#Representations for linbreak definitions.

Community
  • 1
  • 1
oberfreak
  • 1,799
  • 13
  • 20