Command Line Parser

Parsing the Command-line arguments

The very first step in any functionality is always: parsing the string args[] provided in the command-line. Even if you normally won't see this happen, parsing always takes place behind the scenes.

There is one class that does this job: CommandLineParser. This class parses the command-line and creates Verbs, Options and Targets.

private static void Main(string[] args)
{
    CommandLineArguments arguments 
        = CommandLineParser.Parse( args);
    
    foreach (string verb in arguments.Verbs) ..
    foreach (Option option in arguments.Options) ..
    foreach (string target in arguments.Targets) ..
}

See ParseOnly example / ParseOnly project

Case-sensitive or ignore case

You may wonder, how to control whether Option parsing is case-sensitive or if it will ignore cases? The answer is simple: The CommandLineParser always parses case-sensitive.

The reason for this behavior is, the Parser parses the command-line, it does not interpret the provided values. So, for the Parser FILENAME and filename are different strings, which result in different Options (see ParseOnly project).

MayApp.exe verb2 VERB2 --FILENAME='def' --fileName='c:\\myfile.csv'

CommandLineArguments:
Verb='verb2'
Verb='VERB2'
Options[FILENAME] = 'def'
Options[fileName] = 'c:\myfile.csv'

Of course, this is just half the story. However, if you' re using the CommandLineParser you should be aware of this 'sensitive behavior'. You will find the rest of the story and how to configure IgnoreCase in the Commander section.

Settings - to control Option recognition

By providing a Settingsobject you can control how Options are being recognized.

CommandLineArguments arguments = CommandLineParser.Parse( 
    args,
    new Settings
    {
        OptionsTags = new []{ '-', '/'} ,
        OptionValueTags = new [] {' ', ':', '='}
    }

OptionTags - define the tags which mark an Option (note: '--' will also be recognized as an Option tag).

OptionValueTags - define the tag that split an Option name from its value

With the default values, you can specify Options like that:

--Option1
-Option1
/Option2='abc'
/Option2:'abc'
/OPtion2 'abc' --Option3=123 -boolOption=true

Note: If you use Commander.ExecuteCommand() you can also provide a Stettings object to control command-line parsing (see Command Resolution).

Last updated