Compiling/Executing a C# Source File in Command Prompt

Compiling/Executing a C# Source File in Command Prompt

CSC.exe is the CSharp 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:

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

(all on one line)

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 of 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, syntax is similar, only C sharp Compiler is just named csc:

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

Then to run it :

$ mono MyApplication.exe

I want to compile a C# file using command prompt

When you install Visual Studio it comes with it a batch file that sets up the environment for you and opens a cmd window. It's called Developer Command Prompt for VS201x (where x is the Visual Studio version you have). It is located in the Visual Studio Tools menu, usually at:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Visual Studio 201x\Visual Studio Tools

This is the result:

Sample Image

EDIT:

If you don't have Visual Studio installed you can still access the C# compiler shipped with the .NET Framework in Windows 8. You will find it in:

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

Otherwise you can install it manually. Here is the link

What you need to do after is just adding it to your environment variable path

Hope it helps.

How can I compile and run c# program without using visual studio?

If you have .NET v4 installed (so if you have a newer windows or if you apply the windows updates)

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe somefile.cs

or

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.sln

or

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.csproj

It's highly probable that if you have .NET installed, the %FrameworkDir% variable is set, so:

%FrameworkDir%\v4.0.30319\csc.exe ...

%FrameworkDir%\v4.0.30319\msbuild.exe ...

Is it possible to compile a single C# code file with the .NET Core Roslyn compiler?

Yes, it is possible to compile a single file with csc or vbc compilers in .NET Core.

To invoke the Roslyn compiler directly it is necessary to use the command line driver csc.{exe|dll} and since Roslyn in contrast to the old csc.exe does not reference mscorlib.dll implicitly it is necessary to pass a reference to the required dependencies, i.e. System.Runtime and System.Private.CoreLib libraries and any other required references. The following listing shows how to compile the following Hello, World! program.

using System;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}

Using WSL with Ubuntu 16.04 (Xenial Xerus) and dotnet-sdk-2.0.0 installed:

time dotnet /usr/share/dotnet/sdk/2.0.0/Roslyn/csc.exe -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Private.CoreLib.dll -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Console.dll -r:/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.0/System.Runtime.dll HelloWorld.cs
Microsoft (R) Visual C# Compiler version 2.3.2.61921 (ad0efbb6)
Copyright (C) Microsoft Corporation. All rights reserved.

real 0m0.890s
user 0m0.641s
sys 0m0.250s

ls -li
total 4
4785074604720852 -rw-rw-rw- 1 developer developer 178 Dec 7 15:07 HelloWorld.cs
11821949022487213 -rw-rw-rw- 1 developer developer 4096 Dec 7 15:13 HelloWorld.exe

The required dependencies, which are passed to the compiler, are different on different platforms, i.e. on Windows it is enough to pass System.Runtime.dll and System.Console.dll while on Ubuntu 16.04 it is necessary to pass in addition System.Private.CoreLib.dll. Different SDK versions will have Roslyn and command line drivers located in different places - the SDK layout changes between versions - and the newest 2.2.2 SDK ships with csc.dll and vbc.dll instead of csc.exe and vbc.exe. Therefore, before using this method it is necessary to check your SDK layout.

Detailed explanation

The Roslyn compiler was designed in a bit different way than the previously used csc.exe and vbc.exe compilers. First of all, Roslyn is written in C# and VB.NET and is a managed .NET application. On Windows it used mainly as a common service running in a server process VBCSCompiler.exe (.dll). However, Roslyn ships with managed command line drivers, csc.exe and vbc.exe (the latest .NET SDK versions ship with csc.dll and vbc.dll) which can be used to compile source files directly from the command line. Anyway, it is exactly what the build system in .NET does, invoking Roslyn via the command line. Running a simple dotnet csc.exe -help command will print usage information which will guide in using the compiler directly from the command line (see the last listing).

The major difference between old native compilers and Roslyn is due to the fact that the latter is a managed application is a startup time. Roslyn, even after being compiled to R2R native assemblies (Ready To Run), would need to start by loading the whole .NET framework, initializing it and then loading Roslyn assemblies and starting the compilation process. It is always a bit slower than running the native compiler, however, as can be seen from above timings, not that much slower.

There was a new documentation article added to the corefx repository describing Advanced scenario - Build and run application code with csc/vbc and CoreRun. Anyone interested can use it as a guideline how to work at the low level of .NET Core.

    Microsoft (R) Visual C# Compiler version 2.3.2.61921 (ad0efbb6)
Copyright (C) Microsoft Corporation. All rights reserved.


Visual C# Compiler Options

- OUTPUT FILES -
/out:<file> Specify output file name (default: base name of
file with main class or first file)
/target:exe Build a console executable (default) (Short
form: /t:exe)
/target:winexe Build a Windows executable (Short form:
/t:winexe)
/target:library Build a library (Short form: /t:library)
/target:module Build a module that can be added to another
assembly (Short form: /t:module)
/target:appcontainerexe Build an Appcontainer executable (Short form:
/t:appcontainerexe)
/target:winmdobj Build a Windows Runtime intermediate file that
is consumed by WinMDExp (Short form: /t:winmdobj)
/doc:<file> XML Documentation file to generate
/refout:<file> Reference assembly output to generate
/platform:<string> Limit which platforms this code can run on: x86,
Itanium, x64, arm, anycpu32bitpreferred, or
anycpu. The default is anycpu.

- INPUT FILES -
/recurse:<wildcard> Include all files in the current directory and
subdirectories according to the wildcard
specifications
/reference:<alias>=<file> Reference metadata from the specified assembly
file using the given alias (Short form: /r)
/reference:<file list> Reference metadata from the specified assembly
files (Short form: /r)
/addmodule:<file list> Link the specified modules into this assembly
/link:<file list> Embed metadata from the specified interop
assembly files (Short form: /l)
/analyzer:<file list> Run the analyzers from this assembly
(Short form: /a)
/additionalfile:<file list> Additional files that don't directly affect code
generation but may be used by analyzers for producing
errors or warnings.
/embed Embed all source files in the PDB.
/embed:<file list> Embed specific files in the PDB

- RESOURCES -
/win32res:<file> Specify a Win32 resource file (.res)
/win32icon:<file> Use this icon for the output
/win32manifest:<file> Specify a Win32 manifest file (.xml)
/nowin32manifest Do not include the default Win32 manifest
/resource:<resinfo> Embed the specified resource (Short form: /res)
/linkresource:<resinfo> Link the specified resource to this assembly
(Short form: /linkres) Where the resinfo format
is <file>[,<string name>[,public|private]]

- CODE GENERATION -
/debug[+|-] Emit debugging information
/debug:{full|pdbonly|portable|embedded}
Specify debugging type ('full' is default,
'portable' is a cross-platform format,
'embedded' is a cross-platform format embedded into
the target .dll or .exe)
/optimize[+|-] Enable optimizations (Short form: /o)
/deterministic Produce a deterministic assembly
(including module version GUID and timestamp)
/refonly Produce a reference assembly in place of the main output
/instrument:TestCoverage Produce an assembly instrumented to collect
coverage information
/sourcelink:<file> Source link info to embed into PDB.

- ERRORS AND WARNINGS -
/warnaserror[+|-] Report all warnings as errors
/warnaserror[+|-]:<warn list> Report specific warnings as errors
/warn:<n> Set warning level (0-4) (Short form: /w)
/nowarn:<warn list> Disable specific warning messages
/ruleset:<file> Specify a ruleset file that disables specific
diagnostics.
/errorlog:<file> Specify a file to log all compiler and analyzer
diagnostics.
/reportanalyzer Report additional analyzer information, such as
execution time.

- LANGUAGE -
/checked[+|-] Generate overflow checks
/unsafe[+|-] Allow 'unsafe' code
/define:<symbol list> Define conditional compilation symbol(s) (Short
form: /d)
/langversion:<string> Specify language version mode: ISO-1, ISO-2, 3,
4, 5, 6, 7, 7.1, Default, or Latest

- SECURITY -
/delaysign[+|-] Delay-sign the assembly using only the public
portion of the strong name key
/publicsign[+|-] Public-sign the assembly using only the public
portion of the strong name key
/keyfile:<file> Specify a strong name key file
/keycontainer:<string> Specify a strong name key container
/highentropyva[+|-] Enable high-entropy ASLR

- MISCELLANEOUS -
@<file> Read response file for more options
/help Display this usage message (Short form: /?)
/nologo Suppress compiler copyright message
/noconfig Do not auto include CSC.RSP file
/parallel[+|-] Concurrent build.
/version Display the compiler version number and exit.

- ADVANCED -
/baseaddress:<address> Base address for the library to be built
/checksumalgorithm:<alg> Specify algorithm for calculating source file
checksum stored in PDB. Supported values are:
SHA1 (default) or SHA256.
/codepage:<n> Specify the codepage to use when opening source
files
/utf8output Output compiler messages in UTF-8 encoding
/main:<type> Specify the type that contains the entry point
(ignore all other possible entry points) (Short
form: /m)
/fullpaths Compiler generates fully qualified paths
/filealign:<n> Specify the alignment used for output file
sections
/pathmap:<K1>=<V1>,<K2>=<V2>,...
Specify a mapping for source path names output by
the compiler.
/pdb:<file> Specify debug information file name (default:
output file name with .pdb extension)
/errorendlocation Output line and column of the end location of
each error
/preferreduilang Specify the preferred output language name.
/nostdlib[+|-] Do not reference standard library (mscorlib.dll)
/subsystemversion:<string> Specify subsystem version of this assembly
/lib:<file list> Specify additional directories to search in for
references
/errorreport:<string> Specify how to handle internal compiler errors:
prompt, send, queue, or none. The default is
queue.
/appconfig:<file> Specify an application configuration file
containing assembly binding settings
/moduleassemblyname:<string> Name of the assembly which this module will be
a part of
/modulename:<string> Specify the name of the source module

How to Run c# application through Command Prompt?

You should use all files when calling csc. It doesn't try to find the code files itself. Try this:

csc /out:Test.exe Test.cs Entity.cs

Or, maybe easier:

csc /out:Test.exe *.cs

Also, read the related MSDN article.

Don't forget to add this code block in a method too:

namespace Demo
{
public class Entity
{
public void SomeMethod() /* here */
{
Console.WriteLine("entity");
}
}
}

How to compile C# application through Command Prompt

One option to simply build .csproj with MSBUILD.

More entertaining is to configure all dependencies yourself via command line arguments of csc. For your immediate error you need to add references with /r: command similar to following

 csc /out:Test.exe /r:System.ComponentModel.DataAnnotations.dll *.cs

For more details on command line arguments of csc check help csc /? or on MSDN CSC command line options and Building with CSC.



Related Topics



Leave a reply



Submit