Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / C#
Article

Simple Command Line Parser

Rate me:
Please Sign up or sign in to vote.
4.25/5 (4 votes)
9 Nov 20054 min read 49.3K   1.3K   31   8
Command line parsing is the same regardless of the values in the parameters. My classes handle the parsing of the command line so that you can focus on interpreting the data.

Introduction

Command line argument parsing is the same regardless of the values in the parameters. My classes handle the parsing of the command line so that you can focus on interpreting the data that comes from the command line.

Background

I like to write little utility style programs that can help me do my work. I have many of these applications stuck in my path, available at a moment's notice. One thing that I have found in common is for any command line utility to work well, it needs to be able to handle command line arguments. And not just handle the input, but to be graceful about it. But writing that code is tedious. This code is also repetitive for each utility.

So I designed a few classes that handle the mundane task of parsing command line arguments. This allows me to focus my thoughts on the utility program I am writing.

Using the Code

The key class is the ApplicationCommandLine class. The purpose of the ApplicationCommandLine class is to allow application programmers the ability to avoid having to parse the command line, handling all of the complexities of the command line, and allow them to focus on the data given in the command line.

The ApplicationCommandLine class maps program defined data (instances of CommandLineArgument) to actual command line input (that's the Main(String[] args) input).

For the purpose of this discussion, there are two types of inputs received on the command line. Arguments that are delineated with a delimiter such as -, and arguments that are not delineated.

Arguments delineated with a delimiter are called cmdArgs and those that are not will be called fileArgs. The ApplicationCommandLine class handles both types.

One thing to note, not all un-delineated arguments are fileArgs. Some of them could be data for a cmdArg. In such cases, they are called dataArgs. The content for dataArgs is stored in cmdArg class instances if the cmdArg is an instance of DataCommandLineArgument (discussed below).

Example: myprog -c -f notes.txt notes2.txt

-c is a cmdArg
-f is a cmdArg with a dataArg
notes.txt is the dataArg for -f
notes2.txt is a fileArg

In order for ApplicationCommandLine to work correctly, it has to know what to expect to find on the command line. To initialize it, there is a function called AddArg(CommandLineArgument cmd).

The CommandLineArgument class represents a token that can be extracted from the command line parameters. Because there can be different types (as discussed above) of command line arguments there are several classes derived from CommandLineArgument. All of these classes are defined in the CommandLineArgument.cs source file.

  • CommandLineArgument
  • SwitchableCommandLineArgument
  • DataCommandLineArgument

The SwitchableCommandLineArgument is a neat class. It allows you to bind two command line arguments to each other to be exclusive of each other. For example, a light can be either on or off. So your command line parameter might turn the light on or off but it could not do both.

The DataCommandLineArgument class is to be used when the command line parameter requires data with it.

To use the ApplicationCommandLine class, you will need to use two functions that are part of the class: AddArg and ParseCmdLineToArgs. You will also want to implement your own function that iterates through the arguments and converts those values to data useful in your own programs.

The test application does exactly that.

One thing to note: the ApplicationCommandLine class will throw exceptions. Typically, the ParseCmdLineToArgs method will throw exceptions if the input is invalid or the command line input doesn't match what is expected. So, it is important to catch CommandlineException exceptions.

The Test Application

The test application is really the demo, showing how simple it is to use the ApplicationCommandLine class. The code is in the file called test.cs and is included in the demo download. Take a look at these three functions: InitializeArguments() which initializes an instance of the ApplicationCommandLine class using instances of CommandLineArgument; Run(string[] args) which gets everything going; and ArgsToProgramData() which processes the data found from the command line.

In the test application, the Run method is the driver. It initializes the ApplicationCommandLine object instance, calls on the ApplicationCommandLine object instance to process the command line, and then processes the results.

C#
public void Run(string[] args)
{
    // always say something about us
    PrintHeader();

    try
    {
        // initialize the argments expected on the command line
        InitializeArguments();

        // parse the command line 
        _cmdProcessor.ParseCmdLineToArgs(args);

        // convert the command line data to something for the program
        ArgsToProgramData();

    }
    catch(HelpException)
    {
       // my ArgsToProgramData throws a HelpException if the /? 
       // argument is found in the list 
       PrintHelp();
    }
    catch(MattRaffelNetCode.ApplicationSupport.CommandlineException cmdError)
    {
        Console.WriteLine(cmdError.Message);
        Console.WriteLine("try Test /? for help");
    }
    catch(Exception error)
    {
        Console.WriteLine(error.Message);
        Console.WriteLine(error.StackTrace);
    }
    finally
    {
    }

}

Finally

I hope that you find my classes helpful. They work well for me, but that doesn't mean the classes are perfect. Any changes or comments you have, I would appreciate hearing.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralNConsoler - another command line parsing library Pin
Maxim Tihobrazov8-Sep-08 7:31
Maxim Tihobrazov8-Sep-08 7:31 
Generalthanks for the utility Pin
samg_00235-May-08 11:52
samg_00235-May-08 11:52 
GeneralRe: thanks for the utility Pin
mattraffel7-May-08 2:12
mattraffel7-May-08 2:12 
NewsAllow "empty" command lines Pin
Christian Klauser28-Jun-06 6:25
Christian Klauser28-Jun-06 6:25 
GeneralRe: Allow "empty" command lines Pin
mattraffel28-Jun-06 6:48
mattraffel28-Jun-06 6:48 
GeneralA few suggestions... Pin
James Curran10-Nov-05 7:22
James Curran10-Nov-05 7:22 
GeneralRe: A few suggestions... Pin
mattraffel10-Nov-05 7:39
mattraffel10-Nov-05 7:39 
GeneralStraightforward design Pin
Shawn Poulson9-Nov-05 10:19
Shawn Poulson9-Nov-05 10:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.