221

How do you compile and execute a .cs file from a command-prompt window?

1
  • 2
    For those who are interested: I have written a batch file CompileCS.cmd which allows you to compile (and optionally run) a C# file. It uses csc.exe internally and invokes the most recent version found on the local PC. You can find the the batch program 'CompileCS' here at StackOverflow, where I answered how to obtain the most recent csc.exe installed. Commented Jan 11, 2022 at 8:06

20 Answers 20

189

CSC.exe is the C# compiler included in the .NET Framework and can be used to compile from the command prompt. The output can be an executable ".exe", if you use "/target:exe", or a DLL; If you use /target:library. CSC.exe is found in the .NET Framework directory,

e.g. for .NET 3.5, c:\windows\Microsoft.NET\Framework\v3.5\.

To run, first, open a command prompt, click "Start", then type cmd.exe.
You may then have to cd into the directory that holds your source files.

Run the C# compiler like this (all on one line):

c:\windows\Microsoft.NET\Framework\v3.5\bin\csc.exe 
          /t:exe /out:MyApplication.exe MyApplication.cs  ...

If you have more than one source module to be compiled, you can put it on that same command line. If you have other assemblies to reference, use /r:AssemblyName.dll.

Ensure you have a static Main() method defined in one of your classes, to act as the "entry point".

To run the resulting EXE, type MyApplication, followed by <ENTER> using the command prompt.

This article on MSDN goes into more detail on the options for the command-line compiler. You can embed resources, set icons, sign assemblies - everything you could do within Visual Studio.

If you have Visual Studio installed, in the "Start menu"; under Visual Studio Tools, you can open a "Visual Studio command prompt", that will set up all required environment and path variables for command line compilation.

While it's very handy to know this, you should combine it with knowledge of some sort of build tool such as NAnt, MSBuild, FinalBuilder etc. These tools provide a complete build environment, not just the basic compiler.

On a Mac

On a Mac, the syntax is similar, only that the C# compiler is just named csc:

$ csc /target:exe /out:MyApplication.exe MyApplication.cs ...

Then to run the program:

$ mono MyApplication.exe
Sign up to request clarification or add additional context in comments.

6 Comments

if I remember correctly, you can only compile to and exe if you have a static class with a Main method.
The compiler warns you these days if you haven't, but good point I'll add that to the answer, thanks.
In Win10, I found mine there: C:\Program Files (x86)\MSBuild\14.0\Bin\csc.exe
In 2024 the steps are - download .NET 4.8.1 and install it - at the command line use C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /t:exe /out:cs_HelloWorld.exe cs_HelloWorld.cs perfect.
Note that this answer only relates to the (quite outdated) Windows-only .NET Framework. For the more modern, cross-platform .NET (Core), this won't work. There is no "csc.exe" binary (duh!), only a managed "csc.dll" assembly you need to run with dotnet.
|
23

Another way to compile C# programs (without using Visual Studio or without having it installed) is to create a user variable in environment variables, namely "PATH".

Copy the following path in this variable:

"C:\Windows\Microsoft.NET\Framework\v4.0.30319"

or depending upon which .NET your PC have.

So you don't have to mention the whole path every time you compile a code. Simply use

"C:\Users\UserName\Desktop>csc [options] filename.cs"

or wherever the path of your code is.

Now you are good to go.

Comments

19

You can compile a C# program :

c: > csc Hello.cs

You can run the program

c: > Hello

3 Comments

What if I use additional libraries? I'm getting errors that assemblies are not found... How to fix this?
You'd have to make sure first that the path to the compiler is in the environment variables.
@NikasŽalias. E.g. csc Hello.cs -langversion:latest -reference:System.Net.Http.dll
14

For the latest version, first open a Powershell window, go to any folder (e.g. c:\projects\) and run the following

# Get nuget.exe command line
wget https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -OutFile nuget.exe

# Download the C# Roslyn compiler (just a few megs, no need to 'install')
.\nuget.exe install Microsoft.Net.Compilers

# Compiler, meet code
.\Microsoft.Net.Compilers.1.3.2\tools\csc.exe .\HelloWorld.cs

# Run it
.\HelloWorld.exe    

An example HelloWorld.cs

using System;

public class HelloWorld {
    public static void Main() 
    {
        Console.WriteLine("Hello world!");
    }
}

You can also try the new C# interpreter ;)

.\Microsoft.Net.Compilers.1.3.2\tools\csi.exe
> Console.WriteLine("Hello world!");
Hello world!

1 Comment

can create .csproj-file and use new implicit conveniencies starting from .NET-6.0
8

While it is definitely a good thing knowing how to build at the command line, for most work it might be easier to use an IDE. The C# express edition is free and very good for the money ;-p

Alternatively, things like snippy can be used to run fragments of C# code.

Finally - note that the command line is implementation specific; for MS, it is csc; for mono, it is gmcs and friends.... Likewise, to execute: it is just "exename" for the MS version, but typically "mono exename" for mono.

Finally, many projects are build with build script tools; MSBuild, NAnt, etc.

5 Comments

I do use the IDE. But I needed to know. It just doesn't feel right not knowing! Thanks a lot for your response.
+1 for NAnt! LINQPad is very good for experimenting with code fragments: linqpad.net
maintainance of vs_expressis finished long ago, use vs_buildtools or vs_community, last allows commercial production code only for Windows Store marketplace
@JeeyCi in my defence: I was speaking in early 2009
you should not defend, just for readers for the information about nowadays opportunities - I wrote how can be substituted vs_express opportunities that are no more existing
8

I found a simple way to do this if you have the correct system and environmental variables set up and your path is properly configured.

You just need to run in the directory of the project dotnet new console. This will generate the required files such as the .csproj file. It will also generate a Program.cs file which it automatically uses as the entry point, if you have other files with your static Main method you can remove this file and it should find the Main entry point automatically.

Then, all you need to do to run is dotnet run and it should compile and run automatically.

This was how I managed to get my projects working in VS Code using Git Bash as my terminal. Also, I have VS 2019 installed, I used the .NET 5.0 framework from this as my system variables. This was the simplest solution I found for basic console programs. It also allows you to add custom imports in your .csproj file.

2 Comments

This is the answer that I was looking for. I had to find it somewhere else and come back to this question to make sure someone had mentioned it. Also, dotnet build will make a .exe file.
this is minimal NET project file and you can add UseWPF or/and UseWindowsForms like here
7

Here is how to install MSBuild with standalone C# 7.0 compiler which is no longer bundled in the latest .Net Framework 4.7:

Is it possible to install a C# compiler without Visual Studio?

Then just run

"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Roslyn\csc.exe" MyApplication.cs

to compile single source file to executable.

Also note that .Net Core doesn't support compiling single source file without preconfigured project.

1 Comment

in Win10 C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe still is present , for me command csc App.cs /t:exe /reference:myLib.dll /out:App.exe in the source folder - helped, without .proj-file NET.Framework's compiler builds ok
5

PowerShell can execute C# code out of the box.

One liner to compile & execute a file:

(Add-Type -Path "Program.cs" -PassThru)::Main() #'Main' is the entry point

Supposed you have a .cs file like this:

using System;
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello from C#");
    }
}

1 Comment

How would you do this with the newer no-Program-class style CS file? Like it literally contains System.Console.WriteLine("Hello");
2

You can build your class files within the VS Command prompt (so that all required environment variables are loaded), not the default Windows command window.

To know more about command line building with csc.exe (the compiler), see this article.

Comments

2

Add to path

C:\Windows\Microsoft.NET\Framework\v3.5

To Compile:

csc file.cs

To Execute:

file

Comments

2

In Windows systems, use the command csc <filname>.cs in the command prompt while the current directory is in Microsoft Visual Studio&lt;Year>&lt;Version>

There are two ways:

Using the command prompt:

  1. Start --> Command Prompt
  2. Change the directory to Visual Studio folder, using the command: cd C:\Program Files (x86)\Microsoft Visual Studio\2017\ <Version>
  3. Use the command: csc /.cs

Using Developer Command Prompt :

  1. Start --> Developer Command Prompt for VS 2017 (Here the directory is already set to Visual Studio folder)

  2. Use the command: csc /.cs

Comments

2

For .NET (not .NET Framework!), there is a dotnet tool you can install, which is practically a wrapper over the csc binary provided by the Roslyn component of your .NET installation. You can install it globally using this command:

dotnet tool install -g csc

...then, you can verify if it has been installed correctly:

asc@ascpixi:~$ csc -version
4.8.0-7.24225.6 (de75b3c7)

The benefit of using a .NET tool for this is that it stays up-to-date with the .NET runtime host you're currently using to execute the tool (probably from the latest version of the .NET SDK you have installed), and is platform independent when it comes to the setup.

Comments

1

If you have installed Visual Studio then you have Developer Command Prompt for VS. You can easily build your program using csc command and run your application with the name of the application inside the developer command prompt.

You can open Developer command prompt as given below.

Start => Developer Command Prompt for VS

Hope this helps!

4 Comments

can you explain how this actually answers the question? how will this help with using the command line?
@d0rf47 You can easily build your program using csc command and run your application with the name of the application inside the developer command prompt. Did you at least read the answer before commenting and downvoting?? I wonder how two people found this helpful.
of course i read it. i just didnt find it helpful or clear
@d0rf47 OK. Thank you for you for your feedback :)
1
# File    : csharp.ps1
# Purpose : Powershell Script to compile a csharp console application from powershell prompt

try {
    # CSharp Compiler
    #$csc = "C:\Windows\Microsoft.NET\Framework\v3.5\bin\csc.exe"
    $csc = "C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe"
    # NOTE: if this path doesn't work search Framework folder for csc.exe

    $ErrorActionPreference = 'Stop'

    if ($args.Count -eq 0) {
        write-host "`nUSAGE: csharp.ps1 (console_application.cs)"
        exit 1
    }

    $file = $args[0];
    if (-not(test-path $file)) {
        throw "file doesn't exist: $file"   
    }
    
    $cmd = "$csc /nologo  /t:exe  /out:${file}.exe $file"

    write-host  -ForegroundColor Green "`nx: $cmd"
    invoke-expression $cmd  
}   
catch { 
    write-host -ForegroundColor Red "`nEXCEPTION: $_"
}
finally {
    write-host ""
}
// File: helloworld.cs
using System;

namespace MyProgram
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.Write("Hello World...");
            Console.ReadKey(true);
        }
    }
}
PS> .\csharp.ps1 helloworld.cs

1 Comment

This is worth a vote for the all important Console.ReadKey(true);
1

I'm building a dotnet tool executing the C# source file without a project file, hope it helps

https://github.com/WeihanLi/dotnet-exec

Install the dotnet tool first

dotnet tool install -g dotnet-execute

and then execute the csharp source file with dotnet-exec Hello.cs

Comments

0

Once you write the c# code and save it. You can use the command prompt to execute it just like the other code.

In command prompt you enter the directory your file is in and type

To Compile:

mcs yourfilename.cs

To Execute:

mono yourfilename.exe 

if you want your .exe file to be different with a different name, type

To Compile:

mcs yourfilename.cs -out:anyname.exe 

To Execute:

mono anyname.exe 

This should help!

Comments

0

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Roslyn

this is where you can find the c# compiler that supports c#7 otherwise it will use the .net 4 compilers which supports only c# 5

Comments

0
  • Search "Path" in windows
  • Select "Edit the system environment.."
  • Click on "Environment Variable" right bottom
  • Double Click on Path in Variable Section
  • Click on New and add the path (you Want to add)
  • Click Okay Okay Okay

for me to run csc from command Prompt

Added this "C:\Windows\Microsoft.NET\Framework\v4.0.30319" to path

then open command prompt where my file is located, and ran this

PS C:\Users\UserName\Downloads\Mouse> csc.exe Mouse.cs

Comments

0

Within Windows 10 and 11 the current native version of C# and VB Framework compiler is Version 4.8.9232.0.
Usually found at C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe.

It is so good you can write your own IDE for Windows Native CMD files to convert images to PDF faster than the same task in PowerShell.
enter image description here

HOWEVER.
The native 4.8.9232.0 version accepts only C# v5 based code and can cause issues if using more modern cs files, for example including $ it raises a runtime fail to compile.

Microsoft (R) Visual C# Compiler version 4.8.9232.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.

This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to C# 5, which is no longer the latest version. For compilers that support newer versions of the C# programming language, see http://go.microsoft.com/fwlink/?LinkID=533240

multi - Copy.cs(45,27): error CS1056: Unexpected character '$'
multi - Copy.cs(53,27): error CS1056: Unexpected character '$'
multi - Copy.cs(56,27): error CS1056: Unexpected character '$'
multi - Copy.cs(61,27): error CS1056: Unexpected character '$'

One simple Portable solution is to curl down and untar the newer compilers but that can be done simpler by use a cmd file such as this which has the latest 4.14 and earlier 4.2 if you want that.

Either of these downloads does not suffer the above same problem of failing on code newer than C# for v5.

@echo off 
cd /d "%~dp0"
if not exist nuget.exe curl -o nuget.exe https://dist.nuget.org/win-x86-commandline/latest/nuget.exe
if not exist nuget.exe echo test for problem & pause & exit /b
Echo Checking for Current CSC version

goto Latest

REM these are the earlier V4.2 entry points
if not exist Microsoft.Net.Compilers.4.2.0\tools\csc.exe nuget.exe install Microsoft.Net.Compilers
if not exist Microsoft.Net.Compilers.4.2.0\tools\csc.exe echo test for problem & pause & exit /b
Microsoft.Net.Compilers.4.2.0\tools\csc.exe -version

:Latest v4.14
if not exist Microsoft.Net.Compilers.Toolset.4.14.0\tasks\net472\csc.exe nuget.exe install Microsoft.Net.Compilers.Toolset
if not exist Microsoft.Net.Compilers.Toolset.4.14.0\tasks\net472\csc.exe echo test for problem & pause & exit /b
Microsoft.Net.Compilers.Toolset.4.14.0\tasks\net472\csc.exe -version

echo/
pause

Once you have the latest tools add that folder to your path or reference the file in your CMD's. Of course you can still use your C# 5 tools recompiled aswell, as it is backwards compatible.

enter image description here

Comments

-4
dotnet

This is oooold. But since this is where you end up as a beginner when you ask questions to understand how to use C# like C or C++ in a console using compilers without Visual Studio CE (highly recommended for C# btw if you aren't already using it) you end up getting more confused within the lingo of .NET framework and libraries and SDKs. If someone like you stumbles upon my answer as a complete beginner:

1. Understand the difference between Framework and SDK.

2. Understand what C# is and what .NET is.

3. THIS: https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/intro

You'll pick up the rest along the way. But instead of using framework I suggest using the SDK and mostly sticking to VS. As for me, I learned C# for unity and mostly game dev.

Also Google is your friend. Ask Questions, stay curious.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.