Using commandline arguments

Many applications built for the Windows platform accept command-line parameters. To accept command-line parameters within your C# application, you must declare a string array as the only parameter to the Main method, as shown in the following code:

class Class1 {

public static void Main(string[] args) {

foreach (string arg in args)

System.Console.WriteLine(arg);

Here, a typical class contains the Main method. Note that the Main method has one parameter defined, a string array that is to be stored in the args variable. It uses the foreach command to iterate through all the strings that are stored within the args array, and then you write those strings out to the console.

Note If you are using Visual Studio .NET for your C# development, the string array is automatically added for you when you create a console application.

If you were to run the preceding application with no parameters, nothing would happen. If you were to run the application like this:

Sampleap.exe parameter1 parameter2

the output from the application would look like the following:

parameter1 parameter2

Command-line arguments are an excellent way to provide switches to your application; for example, to turn on a log file while your application executes.

0 0

Post a comment