Returns and Parameters on Main()
So far, declaration of an executable’s Main() method has been the simplest declaration possible. You have not included any parameters or non-void return type in your Main() method declarations. However, C# supports the ability to retrieve the command-line arguments when executing a program, and it is possible to return a status indicator from the Main() method.
The runtime passes the command-line arguments to Main() using a single string array parameter. All you need to do to retrieve the parameters is to access the array, as demonstrated in Listing 5.12. The purpose of this program is to download a file whose location is given by a URL. The first command-line argument identifies the URL, and the second argument is the filename to which to save the file. The listing begins with a switch statement that evaluates the number of parameters (args.Length) as follows:
If there are not two parameters, display an error indicating that it is necessary to provide the URL and filename.
The presence of two arguments indicates the user has provided both the URL of the resource and the download target filename.
Listing 5.12: Passing Command-Line Arguments to Main
using System; using System.IO; using System.Net.Http; class Program { static int Main(string[] args) { int result; switch (args.Length) { default: // Exactly two arguments must be specified; give an error Console.WriteLine( "ERROR: You must specify the " + "URL and the file name"); Console.WriteLine( "Usage: Downloader.exe <URL> <TargetFileName>"); result = 1; break; case 2: WebClient webClient = new WebClient(); webClient.DownloadFile(args[0], args[1]); result = 0; break; } return result; } }
The results of Listing 5.12 appear in Output 5.4.
Output 5.4
>Downloader.exe ERROR: You must specify the URL to be downloaded Downloader.exe <URL> <TargetFileName>
If you were successful in calculating the target filename, you would use it to save the downloaded file. Otherwise, you would display the help text. The Main() method also returns an int rather than a void. This is optional for a Main() declaration, but if it is used, the program can return a status code to a caller (such as a script or a batch file). By convention, a return other than zero indicates an error.
Although all command-line arguments can be passed to Main() via an array of strings, sometimes it is convenient to access the arguments from inside a method other than Main(). The System.Environment.GetCommandLineArgs() method returns the command-line arguments array in the same form that Main(string[] args) passes the arguments into Main().