c# - 如何在C#中使用StreamWriter.WriteLine方法写入unix行结束符 '\n'?

标签 c# newline

StreamWriter.WriteLine 自动写入行结束符,但是 StreamWriter.WriteLine 方法的默认行结束符似乎是 \r\n ,对于unix平台是否可以将其更改为\n

我在 Windows 10 上运行代码,它与平台相关吗?我可以在Windows环境下使用StreamWriter.WriteLine输出带有unix endofline终止符\n的文本文件吗?

这是我的代码:

using System;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter sw = new StreamWriter("NewLineText.txt", true);
            for (int i = 0; i < 3; i++)
            {
                sw.WriteLine("new line test" + i);
            }
            sw.Close();
        }
    }
}

最佳答案

StreamWriter.WriteLine write endofline terminator automatically, but It seems that the default endofline terminator for StreamWriter.WriteLine method is '\r\n', is it possible to change it to '\n' for unix platform?

在 Unix 上运行时,它已经使用 \n

I'm running the code on Windows 10, Is it platform-related?

是的。

Can I use StreamWriter.WriteLine to output a textfile with unix endofline terminator '\n' on Windows environment?

是 - 通过更改 NewLine 属性。您所需要做的就是在调用 WriteLine 之前设置属性:

StreamWriter sw = new StreamWriter("NewLineText.txt", true);
sw.NewLine = "\n"; // Use Unix line endings
// Other code as before

顺便说一句,我还建议使用 using 语句,以便适本地处理编写器 - 就我个人而言,我通常会使用 File.AppendText文件.CreateText。所以:

using var writer = File.AppendText("NewLineText.txt");
writer.NewLine = "\n"; // Use Unix line endings
for (int i = 0; i < 3; i++)
{
    writer.WriteLine($"new line test {i}");
}

关于c# - 如何在C#中使用StreamWriter.WriteLine方法写入unix行结束符 '\n'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70201332/

相关文章:

html - 如何使用 CSS 在元素之后而不是元素之前插入换行符?

c# - 使用连续的 TryParse 调用是否是猜测字符串的 'real type' 的可靠方法?

c# - 使用 Unity3D 和 Visual Studio 2013

string - Coldfusion:将新行插入字符串

css - 样式表设置不在 IE 和 Firefox 上的新行中显示 <li> 内容

c - Linux 中的 read 调用是否会在 EOF 处添加换行符?

python - 在字符串中规范化行结束的最pythonic方法是什么?

c# - 在 WPF 用户控件中附加 ICommand

c# - SoudPlayer一次又一次播放同一文件

c# - .net 中请求不等待响应