Porting a .NET Console App to run on Linux

1 minute read

With .NET 2015, as we know .NET has provided first-class cross-platform support. So if you have a Linux or Mac environment, you could run a ASP.NET website in less than 10 minutes. Of course, you would need to do one-time setup which may take anything between 45-60 minutes. But I am sure we will get some Docker images or VHDs that would have the Mono environment setup.

If you are new to running .NET 2015 on Linux, I would recommend reading my article on ASP.NET on Linux

In this post, we will look into porting an existing Console Application to Linux

Few changes to your Console Application

If your console application has been built on a version other than .NET 4.6, you need to upgrade it to .NET 4.6. In your console application properties, you can set your target framework to .NET 4.6 (or .NET 4.5.3 in VS 2015 Preview).

To run this application, we need to create a new file project.json in the same folder where your .csproj file exists

{
    "dependencies": {
        "System.Console": "4.0.0.0",
        "Newtonsoft.Json": "6.0.6",
    },
    "configurations": {
        "net45": { },
        "k10": { }
    }
}

 

Now you have to list down all dependencies like I have mentioned System.Console. I believe this can be created from your Nuget packages.config file.

With these changes you are ready to run this on Linux

Run this application on Linux

Copy the source code into Linux using either wget or git or sftp. Let's assume the code is copied as shown in the directory below

So on your Linux VM, you can run following command in the directory ~/Puneet/console/ConsoleApp_SampleForLinux

kpm restore

This will traverse through your project.json file and get all the dependencies. Note here, your csproj file is of no relevance in this process. Even if your csproj file is not copied to Linux, this process will function correctly

Next, build this code using command

kpm build

If there are no errors, you could simply run the application using the command

k run

A simple Hello World application will give an output as,

And your code is ported successfully to run on Linux!

Updated: