Dump text to file with line breaks

2019-03-01 08:47发布

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?

5条回答
叛逆
2楼-- · 2019-03-01 09:22

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);
     }
 } 
查看更多
Lonely孤独者°
3楼-- · 2019-03-01 09:28

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.

查看更多
Summer. ? 凉城
4楼-- · 2019-03-01 09:34

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");
}
查看更多
女痞
5楼-- · 2019-03-01 09:36

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");
    }
}
查看更多
贼婆χ
6楼-- · 2019-03-01 09:43

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.

查看更多
登录 后发表回答