run single *.cs script from command line

silent_coder picture silent_coder · May 30, 2016 · Viewed 7.2k times · Source

Is there at last a easy way to execute c# script file from command line?

I saw that discussion on github

and according to this thread i think dotnet run Test.cs should do the job.

But for my testclass which is:

using System;
namespace Scripts
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.Out.WriteLine("This is the miracle");
        }
    }
}

it fails

PM> dotnet run .\Test.cs 
dotnet.exe : Object reference not set to an instance of an object.At line:1 char:1

So how could I execute the code in single file using command line in relatively easy manner?


UPD 1: As correctly mentioned by @Lee and @svick dotnet run is for running project. But my initial question was - how to run single file. Maybe some options using roslyn?

Answer

Tomáš Hübelbauer picture Tomáš Hübelbauer · May 6, 2019

I found another solution on Scott Hanselman's blog:

https://www.hanselman.com/blog/CAndNETCoreScriptingWithTheDotnetscriptGlobalTool.aspx

It relies on a .NET CLI tool called dotnet-script, you can find its repository below:

https://github.com/filipw/dotnet-script

To use, it, first install it using dotnet tool install -g dotnet-script

Then you can run dotnet script and use it as a REPL or run dotnet script file.csx to run a file.

To include a NuGet package reference, use #r "nuget: AutoMapper, 6.1.0".