Today we are going to see how to create a self-executable C# application, contained within a single .bat file.
We normally think of C# as a tool for creating applications, large ones, whether web or desktop. Its use as a scripting language is less common, where interpreted languages usually stand out.
However, it is possible to run C# in a way similar to a scripting language, to create small programs that perform an action. To do this, we will take advantage of the fact that .NET programs can be compiled through the command console without much difficulty.
In today’s post, we are going to see a little trick to wrap C# code inside a .bat file so that it self-executes, without the need to provide a compiled .exe file.
Something that, honestly, we are not going to do every day either. But which, in certain situations, can be useful.
Basically, what this file does is execute the steps we would take to install it automatically for us.
// 2>nul||@goto
if not exist “%csc%” ( echo no .net framework installed exit /b 10 )
if not exist ”%~n0.exe” ( call %csc% /nologo /warn:0 /out:”%~n0.exe” ”%~dpsfnx0” || ( exit /b %errorlevel% ) ) %~n0.exe %* endlocal & exit /b %errorlevel% */
using System; using System.Runtime.InteropServices; using System.Diagnostics; using System.Collections.Generic;
public class SelfContainer {
public static void Main(String[] args)
{
var myVariable = 2 + 2;
Console.WriteLine("Run from bat " + myVariable);
}
}
Where we simply have to replace the content of the Main function in the file with the code we want to execute.
The file works through a very clever trick, playing with the @goto label and C# comments. In a first execution as a .bat file, the @goto directive redirects to the top part of the file.
Here, the compilation of the file itself is performed. Since the .bat parts of the file are commented out for C#, the compiler ignores this part, compiling only the lower part of the file and executing it.
Of course, you can save this code as a template and, if you ever need it, you just have to replace the Main code with yours. It’s not necessary to remember everything because

