C# scripting with .NET Core global tool
Image from Pexels by Sora Shimazaki

C# scripting with .NET Core global tool

Using .NET Core global tool to run C# script files

I assume since you are reading this article you are involved in development of applications using C# and .NET platform. Microsoft .NET and C# have been around for quite a while but there is not much talk on haw you can use C# for writing code apart from creating your projects in your IDE of choice and compiling them to executables.

This is typical approach for writing robust applications and that is fine, but from time to time, this whole ceremony of creating a project, adding packages and libraries just to run for example a simple scheduled task that cleans up old logs from IIS seems like and overkill. You might as well just go with PowerShell, batch or even Python for such a task.

It's always nice to know more than one language syntax, but since you are working with something day to day and you are quite comfortable with the syntax, than why don't you just stick to C# and write a simple script with it? Yes, you can do scripting with C# thanks to Roslyn compiler which came around quite while ago, back in 2011. If you alredy have your working environment setup for .NET development, you probably have the CSI installed on your system. Just jump to console and run the following command

csi.exe /?
    

You should get the response similar to something like this

Csi Help

If this is not the case and your system is not able to fins csi.exe but you do have Visual Studio installed than you just probably need to add Roslyn folder to Windows Path environment variable.

Depending on the version and edition of Visual Studio you have installed on your machine, the path to Roslyn compiler binary may vary. This is the path for Visual Studio 2019 Community edition I have installed on my Windows machine that I used to add path to environment variables

SETX PATH "%PATH%;%ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Roslyn"
    

After this, just restart your terminal instance and you should be able to use csi.exe to run you C# scripts.

If you wan to have your terminal customized like the one on images in this article, check out article on Customizing PowerShell terminal with oh-my-posh v3.

Running C# script with csi.exe

As I mentioned, if your environment is setup for .NET development you probably have CSI available on your machine. Without any delay, lets try to execute the following code via csi.exe tool.

using System;

Console.WriteLine(DateTime.Now);

    

I saved this file to my drive as test.csx and I ran it with the simple csi command call from the windows command line.

csi.exe ./test.csx

When the command is executed you'll get the current date and time printed out in the console.

Csi Run

Note

Although .csx file extension is commonly used for C# script files (it is even recognized by Windows as "C# Script Source File"), you can use pretty much any extension for your script file. If it makes easier for your IDE to recognize the syntax you can stick to .cs file extension as well

This is pretty cool, but csi.exe comes with certain limitations such as

  • Unable to use NuGet packages directly in the script
  • You are bond to run on Windows host OS

If these two are not show-stopper for you you can stick to it, but if you need something more powerful and modern than continue reading as we'll explore .NET Core and it's global tool for running C# scripts cross-platform with integrated ability to reference and use NuGet packages directly in the script.

Running C# scripts with dotnet-script tool

With .NET Core came cross-platform compatibility and you are not bound to run your C# written application only on Windows OS. .NET Core applications can run on pretty much anything but most likely apart from Windows you would want to run your code on Linux.

Microsoft introduced global tools concept with release of .NET Core 2.1 version. It is pretty easy to write one which I explained in one of the articles Building and using advanced .NET Core CLI global tools and to distribute them via NuGet.

To install dotnet-script global tool you need to run the following command

dotnet tool install dotnet-script --global --ignore-failed-sources
    

Once you have installed the tool, you can start using it and you can test it by running the previous sample scirpt file

dotnet script /temp/test.csx

Now let's try to do something more complex. I'll use Newtonsoft.Json NuGet package to serialize a simple POCO class and display it in console output

#r "nuget: Newtonsoft.Json, 13.0.1"

using System;
using Newtonsoft.Json;

class DateAndTime{
    public String Date {get;set;}
    public String Time {get;set;}
}

var dateAndTime = new DateAndTime(){
    Date= DateTime.Now.ToString("yyyy-MM-dd"),
    Time= DateTime.Now.ToString("HH:mm:ss")
};

Console.WriteLine(JsonConvert.SerializeObject(dateAndTime, Formatting.Indented));

    

Dotent Script Run

You can see that script above starts with the following line

#r "nuget: Newtonsoft.Json, 12.0.3"
    

This is not C# syntax, but rather pre-processing instruction for dotnet-script executable do acquire the package of specific version prior to executing the code.

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article