为什么换行符不起作用?

Pra*_*hal 1 c# io

我是C#文件处理的新手,我正在制作一个非常简单的程序.代码如下:

class MainClass 
{
    public static void Main()
    {
        var sw = new StreamWriter("C:\\Users\\Punit\\Desktop\\hello.txt");
        sw.Write("HelloWorld" +Environment.NewLine);
        sw.Write("ByeWorld");
        sw.Close(); 

        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码在文本文件中产生以下预期结果:

HelloWorld
ByeWorld
Run Code Online (Sandbox Code Playgroud)

我还写了一些像这样修改过的代码版本:

class MainClass 
{
    public static void Main()
    {
        var sw = new StreamWriter("C:\\Users\\Punit\\Desktop\\hello.txt");
        sw.Write("HelloWorld\n");
        sw.Write("ByeWorld");
        sw.Close(); 

        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

这里不使用

Environment.Newline
Run Code Online (Sandbox Code Playgroud)

我直接将"\n"添加到"HelloWorld"行.这产生了以下输出(在文本文件中):

HelloWorldByeWorld
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么第二段代码不起作用?(不在文本文件中生成换行符)

Roh*_*hit 8

请试试

  StreamWriter sw = new StreamWriter("C:\\Users\\Punit\\Desktop\\hello.txt");
    sw.Write("HelloWorld \r\n");
    sw.Write("ByeWorld");
    sw.Close(); 
    Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读