Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to WriteAllLines in C# without CRLF

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.

like image 379
jared Avatar asked Jun 11 '12 22:06

jared


People also ask

How to use WriteAllLines in c#?

WriteAllLines(String, String[], Encoding) is an inbuilt File class method that is used to create a new file, writes the specified string array to the file by using the specified encoding, and then closes the file. Syntax: public static void WriteAllLines (string path, string[] contents, System. Text.

Does file WriteAllLines overwrite?

Remarks. If the target file already exists, it is overwritten. The default behavior of the WriteAllLines method is to write out data using UTF-8 encoding without a byte order mark (BOM).


2 Answers

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

like image 103
Jon Skeet Avatar answered Oct 16 '22 05:10

Jon Skeet


@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);
        }
    }
}
like image 41
Drew Noakes Avatar answered Oct 16 '22 05:10

Drew Noakes