Wednesday, February 27, 2008

Compiling C# programs from console window

A very simple thing. The easy method is to select Visual Studio 200X command prompt from the Visual Studio Tools submenu of your studio installation in the Start -> Programs menu. Path to csc.exe (the C# compiler) will be set automatically.

If you are selecting a standard command prompt (Start -> Run -> cmd) or the Power Shell, you need to set the path to csc.exe. For that, first you should know the location of csc.exe. As you know, .NET framework has different versions, such as 1.1, 2.0, 3.5 etc. When you install a framework, corresponding folder will be created under the %SYSTEMROOT%\Microsoft.NET\Framework directory. For example, on my laptop, there are two folders - v1.1.4322 and v2.0.50727 inside the C:\WINDOWS\Microsoft.NET\Framework directory. csc.exe will be present in both folders. Once you are sure about which version to use, you need to set the PATH environment variable. To make the change temporary, execute the following command.

D:\> SET PATH = %PATH%;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

To make the path change permanent, you need to set the PATH environment variable under the system variables section. For that, select System Properties (Right click on My Computer -> Properties) and click on Environment Variables button in the Advanced tab. Select the PATH variable under the System Variables list and click Edit. Move towards the end of text that appears in the Variable Value text box, put a semicolon (;) and then add the above mentioned folder. Click OK and apply the changes. Now, whenever you fire a new command window, the path will be automatically set. The steps given above are for a Windows XP machine. There should not be any major change in other systems such as Windows 2000 or 2003.
The C# compiler has lot of options. For the complete list, click on this link. The simplest option is to specify csc {filename.cs} from the command prompt (without the { } symbols).

No comments: