How can I write code that works differently for different operating systems?

I am Writing a File I/O code

I found out that each OS use different newline characters

so I wanna make a code that works differently for each OS
like below code

if(isWindows)
{
    Console.Write("Hello World\r\n");
}
else
{
    Console.Write("Hello World\n");
}

Please let me know if you know a good way!

  • 5

    Did you try System.Environment.NewLine?

    – 




  • Is there a reason why you don’t use Console.WriteLine() instead?

    – 

  • learn.microsoft.com/en-us/dotnet/api/… – if you don’t like the character Console.WriteLine produces consider the remark You can change the line terminator by setting the TextWriter.NewLine property of the Out property to another string.

    – 

If you only want to check for line breaks, you can use System.Environment.NewLine. This will return \r\n for non-Unix platforms and \n for Unix platforms.

Console.Write("Hello World" + System.Environment.NewLine);

However, if you need to implement separate code logic for each operating system, you could use RuntimeInformation.IsOSPlatform. This method can identify the following platforms:

  • FreeBSD
  • Linux
  • OSX
  • Windows

Your code would look something like this:

if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
{
    Console.Write("Hello World\r\n");
}
else
{
    Console.Write("Hello World\n");
}

Leave a Comment