Language: EN


How to create a self-executable .bat application with .NET

Today we are going to see how to create a self-executable C# application contained in a .bat file.

We normally think of C# as a tool for creating applications, whether they are web or desktop. Its use as a scripting language is less common, as interpreted languages typically stand out in this area.

However, it is possible to execute C# in a manner 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 prompt 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 don’t do every day. But in certain situations, it can be useful.

Basically, what this file does is execute the steps that we will restart and install automatically for us.

// 2>nul||@goto :batch
@echo off
rem del /q /f "%~n0.exe" >nul 2>nul
:: find csc.exe
set "csc="
for /r "%SystemRoot%\Microsoft.NET\Framework\" %%# in ("*csc.exe") do  set "csc=%%#"

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 that we want to execute.

The file works by using a very clever trick, playing with the @goto directive and C# comments. In the first execution as a .bat file, the @goto directive redirects to the top of the file.

Here, the file itself is compiled. Since the parts of the .bat file are commented for C#, the compiler ignores this part and only compiles and executes the lower part of the file.

So, you can save this code as a template and, if you ever need it, you just have to replace your Main code. You don’t need to remember everything because of this.

And this way you have a very simple way to generate self-executable .bat files that contain code in the C# language. Until next time!