Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compile and run a csharp file using dockerfile

How can I compile a single file (or several) for a simple csharp application using a docker file? My goal is to create a small csharp repl similar to the w3 schools one here. I’ve taken a look at this question but it does not suit my needs. I do not have a .csproj file, I am starting with a simple main.cs file like this:

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass {
    static void Main() {
        Console.WriteLine("Hello World!");
    }
}

I would like to know I can take the above code as a string and use a dockerfile to compile and run it to get the output. Specifically, what base image can I use and do I need to install any other packages before I can do this? The dockerfile below is taken from the other stack overflow question which seems reasonable but I don’t want to compile an asp.net program.

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /app

COPY <your app>.csproj .
RUN dotnet restore <your app>.csproj

COPY . .
RUN dotnet publish -c Release -o out

FROM microsoft/dotnet:2.2-aspnetcore-runtime AS runtime
WORKDIR /app
COPY --from=build /app/out ./

ENTRYPOINT ["dotnet", "<your app>.dll"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the command dotnet new console to create a basic console app project and then copy your file on top of the generated Program.cs file to replace it.

I’ve taken the liberty of replacing your .NET core 2.2 images with .NET 6.0 ones, as the 2.2 ones aren’t supported anymore.

If you name your file with the code in it ‘MyFile.cs’ and use this Dockerfile, it should work

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /app
RUN dotnet new console
COPY MyFile.cs Program.cs
RUN dotnet publish -c Release -o out

FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app/out .
ENTRYPOINT ["dotnet", "app.dll"]

Build and run with

docker build -t testimage .
docker run --rm testimage
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading