public
Created

compile and run small blocks of C# in the command-line

  • Download Gist
cs.bat
Batchfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
@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%
test.txt.cs
C#
1 2 3 4 5 6 7 8
Console.WriteLine("Hello world");
Console.WriteLine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase));
Console.WriteLine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory);
Console.WriteLine(Environment.GetCommandLineArgs()[0]);
Console.WriteLine(System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]));
Console.WriteLine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath);
Console.WriteLine(Environment.CurrentDirectory);
z.sample usage command line output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
C:\Users\Travis>cs test.txt.cs
Hello world
file:\C:\Users\Travis\AppData\Local\Temp
C:\Users\Travis\AppData\Local\Temp
C:\Users\Travis\AppData\Local\Temp\
C:\Users\Travis\AppData\Local\Temp\~temp.2758.exe
C:\Users\Travis\AppData\Local\Temp
 
C:\Users\Travis
 
C:\Users\Travis>cs test.txt
Hello world
file:\C:\Users\Travis\AppData\Local\Temp
C:\Users\Travis\AppData\Local\Temp
C:\Users\Travis\AppData\Local\Temp\
C:\Users\Travis\AppData\Local\Temp\~temp.28538.exe
C:\Users\Travis\AppData\Local\Temp
 
C:\Users\Travis
 
C:\Users\Travis>cs Console.WriteLine("Hello world");
Hello world
 
C:\Users\Travis>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.