Last Updated: February 25, 2016
·
964
· dieseltravis

Compile and run small blocks of C# directly from the command-line

Using this batch file, cs.bat:

@echo off
:: see if %1 exists, if not check for %1.cs
set CODE=%1
IF NOT EXIST %CODE% set CODE=%1.cs
:: init paths
set NETPATH=%systemroot%\Microsoft.NET\Framework64\v4.0.30319
set TEMP_CS=%temp%\~temp.%random%.cs
set TEMP_EXE=%temp%\~temp.%random%.exe
:: init source class
echo using System; class P { static void Main() { > %TEMP_CS%
:: see if code file exists, if not treat args as c#
IF EXIST %CODE% type %CODE% >> %TEMP_CS%
IF NOT EXIST %CODE% ECHO %* >> %TEMP_CS%
echo }} >> %TEMP_CS%
:: compile source, remove source, run exe, remove exe
%NETPATH%\csc /nologo /out:%TEMP_EXE% %TEMP_CS%
del %TEMP_CS%
%TEMP_EXE%
del %TEMP_EXE%

Then you can run something like this: cs Console.WriteLine("Hello world");
or you can pass in a link to a single C# plain-text file too, like: cs some-code.cs

Fork the gist here: https://gist.github.com/3018417