obnews
obnews

Reputation: 612

How to use StreamWriter.WriteLine method to write unix endofline terminator '\n' in C#?

StreamWriter.WriteLine write endofline terminator automatically, but It seems that the default endofline terminator for StreamWriter.WriteLine method is \r\n, is it possible to change it to \n for unix platform?

I'm running the code on Windows 10, Is it platform-related? Can I use StreamWriter.WriteLine to output a textfile with unix endofline terminator \n on Windows environment?

Here is my code:

using System;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter sw = new StreamWriter("NewLineText.txt", true);
            for (int i = 0; i < 3; i++)
            {
                sw.WriteLine("new line test" + i);
            }
            sw.Close();
        }
    }
}

Upvotes: 3

Views: 1825

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502496

StreamWriter.WriteLine write endofline terminator automatically, but It seems that the default endofline terminator for StreamWriter.WriteLine method is '\r\n', is it possible to change it to '\n' for unix platform?

It will already use \n when running on Unix.

I'm running the code on Windows 10, Is it platform-related?

Yes.

Can I use StreamWriter.WriteLine to output a textfile with unix endofline terminator '\n' on Windows environment?

Yes - by changing the NewLine property. All you need to do is set the property before you call WriteLine:

StreamWriter sw = new StreamWriter("NewLineText.txt", true);
sw.NewLine = "\n"; // Use Unix line endings
// Other code as before

As an aside, I'd also suggest using a using statement so that the writer is disposed appropriately - and personally I'd generally use File.AppendText or File.CreateText. So:

using var writer = File.AppendText("NewLineText.txt");
writer.NewLine = "\n"; // Use Unix line endings
for (int i = 0; i < 3; i++)
{
    writer.WriteLine($"new line test {i}");
}

Upvotes: 10

Code Name Jack
Code Name Jack

Reputation: 3313

I would suggest you use Write instead of WriteLine or write an extension method.

public static class UnixStreamWriter
{
   public static void WriteLineUnix(this StreamWriter writer, string value)
   {
       writer.Write(value+"\n");
   }
}

then you can call it like,

StreamWriter sw = new StreamWriter("NewLineText.txt", true);
for (int i = 0; i < 3; i++)
{
   sw.WriteLineUnix("new line test" + i);
}
sw.Close();

Upvotes: -2

Related Questions