Fabrizio Migotto Fabrizio Migotto - 2 months ago 30
C# Question

Change the end of line of a row with File.WriteAllLines();

I'm trying to write a file with this

File
class method in C#.

public static void WriteAllLines(string path, IEnumerable<string> contents);


The end of line is
CRLF
but I need this to be
LF
.

Answer

WriteAllLines uses a StreamWriter to write the lines to a file, using the newline string specified in the NewLine property.

You can use the StreamWriter in your own code and use \n instead of \r\n. This has the benefit that you avoid string concatenations and generating temporary strings :

using (var writer = new StreamWriter(path)) 
{
    writer.NewLine = "\n";
    foreach (var line in contents) 
    {
        writer.WriteLine(line );
    }
}

Using a StreamWriter directly allows you to use asynchronous methods as well:

public async Task MyMethod()
{
    ....
    using (var writer = new StreamWriter(path)) 
    {
        writer.NewLine = "\n";
        foreach (var line in contents) 
        {
            await writer.WriteLineAsync(line);
        }
    }
    ....
}

This can be a big benefit when writing large files, in server and web applications and web sites where you want to keep blocking at a minimum