17

I'm using C# and am trying to output a few lines to an ASCII file. The issue I'm having is that my Linux host is seeing these files as:

ASCII text, with CRLF line terminators

I need this file to be just:

ASCII text

The CRLF is causing some issues and I was hoping there was a way in C# to just create the file formatted in the way I want.

I'm basically using this code:

string[] lines = { "Line1", "Line2" };
File.WriteAllLines(myOutputFile, lines, System.Text.Encoding.UTF8);

Is there an easy way to create the file without the CRLF line terminators? I can probably take care of it on the Linux side, but would rather just create the file in the proper format from the beginning.

DerApe
  • 3,097
  • 2
  • 35
  • 55
jared
  • 1,344
  • 4
  • 20
  • 38
  • The MSDN .NET documentation for the String class might be useful to you, especially the Replace() method. See http://msdn.microsoft.com/en-us/library/system.string.aspx – mikurski Jun 12 '12 at 00:07

2 Answers2

40

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.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I believe the above might be better as File.WriteAllText(myOutputFile, string.Join("\n", lines) + "\n"); because string,Join places separators between elements, but the delimiter must occur after the end of every element, otherwise you'll lose the last line. – Kev Bo Jun 07 '17 at 22:49
  • @KenBoorom: " but the delimiter must occur after the end of every element, otherwise you'll lose the last line." - you won't lose the last line, it just won't have a line break at the end. I'll add that as an option though. – Jon Skeet Jun 08 '17 at 04:03
  • Thank you for adding this option. On linux, POSIX mandates that the last line has to be terminated this way, and many programs rely on this. They indeed would effectively lose last line if it is not terminated this way. – Andrew Savinykh Mar 04 '19 at 01:39
8

@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);
        }
    }
}
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742