Write, Compile and Run a C# program in a single batch file

Mark Mo
2 min readJul 5, 2019

--

I’m sure this has been done many times but this is the first time I’ve done it.

First I need to find my csc.exe. I can do that with this command.

dir %WINDIR%\Microsoft.NET\Framework64\csc.exe /s/b

Here is the output. Copy the full path.

Next I create a batch files that looks like this. I put in the path to my CSC.exe in the next to the last line. Here is the code.

echo using System; >> C:\TEMP\TEST.CS
echo namespace CompileFromBatch >> C:\TEMP\TEST.CS
echo { >> C:\TEMP\TEST.CS
echo class Program >> C:\TEMP\TEST.CS
echo { >> C:\TEMP\TEST.CS
echo static void Main(string[] args) >> C:\TEMP\TEST.CS
echo { >> C:\TEMP\TEST.CS
echo System.Diagnostics.Process.Start("calc.exe"); >> C:\TEMP\TEST.CS
echo } >> C:\TEMP\TEST.CS
echo } >> C:\TEMP\TEST.CS
echo } >> C:\TEMP\TEST.CS
C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\csc.exe -nologo C:\TEMP\TEST.CS
C:\TEMP\TEST.EXE

Here is what that should look like. I’m just using notepad. The path to the CSC.exe is really the only variable between systems. I would automate that but I’m short on time.

I’m saving my example to my C:\Temp\test.bat.

When I double click on it here is the output.

The test.CS file gets created and compiled and calc.exe gets run.

Here is the program that gets created with the batch file.

Nothing special to see, I just needed a break from studying for a certification. When time permits I plan to do something a lot more fun. Feel free to follow me on twitter ( https://twitter.com/_markmo_) or @_markmo_

--

--

Mark Mo

@fashionproof.bsky.social on bluesky @_markmo_ on twitter