Run single * .cs script from command line

Is there finally an easy way to execute a C # script file from the command line?

I saw that github discussion

and according to this topic, I think dotnet run Test.cs should do the job.

But for my test class:

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

he 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 code in a single file using the command line relatively easily?


UPD 1: As correctly indicated by @Lee and @svick dotnet run to start a project. But my initial question is: how to run a single file. Perhaps some options with roslyn ?

+8
source share
4 answers

Pretty sure you'll need a project.json file. Here is a file with empty bones to run it:

 { "dependencies": { "Microsoft.NETCore.App": { "version": "1.0.0-*", "type": "platform" } }, "frameworks": { "netcoreapp1.0": { "imports": {} } }, "buildOptions": { "emitEntryPoint": true } } 

Pay attention to emitEntryPoint .

First I had to dotnet restore , and then dotnet run test.cs

+1
source

This can be done using Powershell. Suppose your code is in the test.cs file in the current folder:

 $source = (Get-Content .\test.cs) -join " " Add-Type $source -Language CSharp [Scripts.Program]::Main(("")) 

gives

 PS> .\test.ps1 This is the miracle 

So, how can I execute code in a single file using the command line in a relatively simple way?

Paste the above code into a function, make the file name a parameter, put this function in your Powershell profile and run it whenever you want. But keep in mind that as soon as you need other assemblies, they must be specified when making the call. Here is a slightly more detailed example .

+1
source

For this, I always used this C # engine: http://csscript.net ,

very easy to implement and works very well, and you can reference local DLLs, Nuget packages, or GAC assemblies.

0
source

I found another solution on Scott Hanselman's blog:

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

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

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

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

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

To include a link to the NuGet package, use #r "nuget: AutoMapper, 6.1.0" .

0
source

All Articles