以换行符将文本转储到文件中


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);
    }
}

将txtChange的文本转储为文本文件。txtChange是一个富文本框,里面有换行符(新行)。

当用户单击Dump按钮时,所有文本将被转储,但不包含新行。

。txtChange看起来像

1
2
3
4

转储文本看起来像1234

我如何格式化文本的转储,使文本在新的行上?

您应该使用Lines属性:

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

你真的不需要使用流,因为File类包含了这些静态方便的方法——简短而切中要害。

上面的

将用文本框txtChange中包含的文本行替换任何现有内容。如果您想要附加内容,请使用适当命名的File.AppendAllLines()

添加一个换行字符:

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 + "rn");
    }
}

如果它包含您提到的r's,您应该尝试这个

using (StreamWriter sw = new StreamWriter("E:\TestFile.txt"))
{
    // Add some text to the file.
    sw.WriteLine(txtChange.Text.Replace("r", "rn");
}

您还可以:

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);
     }
 } 

看一下c#字符串中的替换换行符,替换所有换行符,使其符合Windows标准。

请查看http://en.wikipedia.org/wiki/Newline#Representations以了解linbreak的定义

最新更新