Skip to content

Instantly share code, notes, and snippets.

@dieseltravis
Created June 29, 2012 14:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dieseltravis/3018417 to your computer and use it in GitHub Desktop.
Save dieseltravis/3018417 to your computer and use it in GitHub Desktop.
compile and run small blocks of C# in the command-line
@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%
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);
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>
@dieseltravis
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment