65.9K
CodeProject is changing. Read more.
Home

Fast Scripting via C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (21 votes)

Jun 16, 2018

CPOL

1 min read

viewsIcon

29437

Quick and simple

Often, there is a need to quickly write a small script, with absolutely no desire to understand the syntax of bat-files or create a whole project for these cases.

There is one way to quickly write the script in C# without unnecessary movements.

First, create a new text file and change extension to *.csx:

Next, open file in your favourite code editor (I am using Visual Studio) and write the needed code:

Running

You can run this code in several ways:

  1. Simplest - open file by csi.exe (%programfiles(x86)%\MSBuild\14.0\Bin\csi.exe or %programfiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Roslyn):
  2. You can run code in Visual Studio. Select all text and click «Execute in interactive»

  3. By developer command prompt:

    And do this command:

    csi <path_to_csx>

Result

  • +Written in C#
  • +Fast
  • +IDE pluses (IntelliSense, etc.)
  • - Requires csi.exe (by default in .NET Framework)

Using Libraries

Simple! Write:

#r "MyLib.dll"

in the beginning of *.csx file and copy DLLs to "bin" folder (create this folder near the your script file).
Sample:

MyScript.csx
Bin/MyLib.dll

About CSI

Csi.exe is the Microsoft's command line RELP (read-evaluate-print-loop) tool.

It enables the use of C# as a scripting language by executing source code files directly. The source code IS the executable, so it is easy to make changes and there is no need to maintain a separate EXE file. CSI compiles source code "on the fly" and executes the resulting assembly seamlessly.

This tool uses Microsoft .NET Compiler Platform ("Roslyn") like a "C# Interactive" window in Visual Studio.