With StreamWriter doesn't work \n (C#)

2019-02-08 13:57发布

I have a problem with the C# Stream Writer. I use the following Code:

//Constructor
public EditorTXTFile
{
   FileStream f = File.Create(System.IO.Directory.GetCurrentDirectory() + "\\Output.txt");
   f.Close();
}

//Function AddText
public void AddLogFileText(string text)
{         
   string text = "l1\n\rl2\n\rl3\n\nl5";

   StreamWriter writer = new StreamWriter(System.IO.Directory.GetCurrentDirectory() + "\\Output.txt", true);
   writer.Write(text);         

   writer.Close();
}

When I open Output.txt it shows for \n or \r a █(which means not showable symbol) and the whole string is in one line... Later should the text hand over the function, so I can't write the text with .WriteLine because I don't know if the actual string is on the same line or in a new line.

What make I wrong?

Thanks for any help.

6条回答
手持菜刀,她持情操
2楼-- · 2019-02-08 14:10

i tried to write a class and seprate "\n"s but i found rich text box!!

yeah! it works:

        RichTextBox rch = new RichTextBox();
        rch.Text = cmn;
        foreach (string l in rch.Lines)
            strw.WriteLine(l);
查看更多
叼着烟拽天下
3楼-- · 2019-02-08 14:17

Line Separator(newLine) is \r\n not \n\r,

change your text as :

       string text = "l1\r\nl2\r\nl3\r\nl5";
查看更多
Animai°情兽
4楼-- · 2019-02-08 14:19

Use Environment.NewLine as line separator or "\r\n" if you want to do it by hand.

查看更多
看我几分像从前
5楼-- · 2019-02-08 14:21

This is binary format:

writer.Write(text); 

This is line sequential format:

writer.WriteLine(text); 

You have to use WriteLine format...

查看更多
Juvenile、少年°
6楼-- · 2019-02-08 14:25

Try string text = @"l1\n\rl2\n\rl3\n\nl5";. To prevent character stuffing.

查看更多
forever°为你锁心
7楼-- · 2019-02-08 14:34

You can use Environment.NewLine like this:

streamWriter.Write(String.Concat(Enumerable.Repeat(Environment.NewLine, n).ToArray()));
查看更多
登录 后发表回答