Search code examples
c#operating-systemplatform

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!


Solution

  • 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");
    }