How to WriteAllLines in C# without CRLF

半腔热情 提交于 2019-11-28 10:59:26

Assuming you still actually want the linebreaks, you just want line feeds instead of carriage return / line feed, you could use:

File.WriteAllText(myOutputFile, string.Join("\n", lines));

or if you definitely want a line break after the last line too:

File.WriteAllText(myOutputFile, string.Join("\n", lines) + "\n");

(Alternatively, as you say, you could fix it on the Linux side, e.g. with dos2unix.)

@JonSkeet's answer is a quick and simple solution. It's downside is that it allocates a single string containing all lines of text prior to writing to the file. For large amounts of text, this can put pressure on the memory management system.

An alternative that allows streaming lines without extra allocation is:

public static void WriteAllLines(
    string path, IEnumerable<string> lines, string separator)
{
    using (var writer = new StreamWriter(path))
    {
        foreach (var line in lines)
        {
            writer.Write(line);
            writer.Write(separator);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!