Fabrizio Migotto
Fabrizio Migotto

Reputation: 297

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.

Upvotes: 0

Views: 2122

Answers (5)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131433

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

Upvotes: 6

James Harcourt
James Harcourt

Reputation: 6379

I'd go with this, it avoids re-writing to memory and works quickly. This assumes you are only using ASCII and don't need to overwrite the file - otherwise use a different encoding and change the file mode accordingly.

    public static void WriteAllLines(string path, IEnumerable<string> contents)
    {
        using (var s = new FileStream(path, FileMode.Append))
        {
            foreach (var line in contents)
            {
                var bytes = Encoding.ASCII.GetBytes($"{line}\r");
                s.Write(bytes,0,bytes.Length);
            }
            s.Flush();
            s.Close();
        }
    }

Upvotes: 0

Daniel Kravetz Malabud
Daniel Kravetz Malabud

Reputation: 783

            var builder = new StringBuilder();
            for (int i = 0; i < 99999; i++)
            {
                builder.Append(i.ToString() + '\n');
            }

            File.WriteAllText("asd.txt", builder.ToString());

That is obviously with boilerplate code. Keep in mind that using a StringBuilder instead of a string[] is also faster.

enter image description here

Upvotes: 0

itsme86
itsme86

Reputation: 19496

Instead of using WriteAllLines(), you can join the strings yourself and use WriteAllText():

File.WriteAllText(string path, string.Join("\n", contents) + "\n");

Upvotes: 0

Joe Enos
Joe Enos

Reputation: 40403

There are so many ways of writing to a file, I'd just go with a different one - only a couple lines:

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

Upvotes: 2

Related Questions