Monday, July 12, 2010

Accepting Command Line Arguments - C#

Often times it is useful or necessary to let the user input arguments in command prompt prior to the program being run. These arguments are called command line arguments.

In order to access these arguments, we must use the Main functions single parameter: args.

static void Main(string[] args)
{
}

The command line arguments are stored in the array args. The first one can be accessed at args[0], the second at args[1]...etc.

Note: Since args is simply an array of user inputs, it is good to check to make sure the user inputted correctly formed arguments.

Here is an example of a code that requires one argument. It checks if the user used command line arguments, and if not, prompts the user for input.

Code:
static void Main(string[] args)
        {
            string dir = null;

            if (args.Length == 1)
            {
                dir = args[0];
            }
            else
            {
                Console.WriteLine("Please Enter Path: ");
                dir = Console.ReadLine();
            }

            start(dir);
        }

0 comments:

Post a Comment