Command-Line C# Compilation and Execution
This guide details compiling and running C# code (.cs files) directly from your command prompt.
Using the C# Compiler (csc.exe)
Access your command prompt (Windows: Start > cmd.exe; macOS: Terminal).
Use the cd
command to navigate to the directory containing your .cs file.
Compile using the csc.exe
compiler:
<code class="language-bash">csc.exe /t:exe /out:MyApplication.exe MyApplication.cs</code>
/t:exe
: Specifies an executable file as the output./out:MyApplication.exe
: Sets the output executable's name and path. You can change MyApplication.exe
to your desired name.MyApplication.cs
: Your C# source code file.Running Your Executable
After successful compilation, execute the created file:
<code class="language-bash">MyApplication.exe</code>
(On Windows, omit the .exe
extension if you're already in the directory containing the executable).
Alternative Approaches
Visual Studio Developer Command Prompt
If you have Visual Studio installed, use its developer command prompt (accessible from the Start menu). This pre-configures the necessary environment variables.
Build Tools for Advanced Projects
While the command-line compiler is useful, consider build tools like NAnt, MSBuild, or FinalBuilder for more complex projects and streamlined build processes.
macOS Compilation and Execution
On macOS, the process is similar:
Compilation:
<code class="language-bash">$ csc /target:exe /out:MyApplication.exe MyApplication.cs</code>
Execution:
<code class="language-bash">$ mono MyApplication.exe</code>
Remember to replace MyApplication.exe
and MyApplication.cs
with your actual file names.
The above is the detailed content of How Do I Compile and Run C# Code from the Command Prompt?. For more information, please follow other related articles on the PHP Chinese website!