Best way to handle command line options in C#

12,231

Solution 1

I would recommend using a library such as Command Line Parser to handle this. It supports, out of the box, optional arguments with verb commands such as your example.

Solution 2

I suggest you try using NDesk.Options;, which is a "callback-based program option parser for C#".

OptionSet currently supports:

Boolean options of the form: -flag, --flag, and /flag. Boolean parameters can have a `+' or `-' appended to explicitly enable or disable the flag (in the same fashion as mcs -debug+). For boolean callbacks, the provided value is non-null for enabled, and null for disabled.
    Value options with a required value (append `=' to the option name) or an optional value (append `:' to the option name). The option value can either be in the current option (--opt=value) or in the following parameter (--opt value). The actual value is provided as the parameter to the callback delegate, unless it's (1) optional and (2) missing, in which case null is passed.
    Bundled parameters which must start with a single `-' and consists of a sequence of (optional) boolean options followed by an (optional) value-using option followed by the options's vlaue. In this manner,
-abc would be a shorthand for -a -b -c, and -cvffile would be shorthand for -c -v -f=file (in the same manner as tar(1)).
    Option processing is disabled when -- is encountered.

Here is an example from the docs:

bool show_help = false;
List<string> names = new List<string> ();
int repeat = 1;

var p = new OptionSet () {
    { "n|name=", "the {NAME} of someone to greet.",
       v => names.Add (v) },
    { "r|repeat=", 
       "the number of {TIMES} to repeat the greeting.\n" + 
          "this must be an integer.",
        (int v) => repeat = v },
    { "v", "increase debug message verbosity",
       v => { if (v != null) ++verbosity; } },
    { "h|help",  "show this message and exit", 
       v => show_help = v != null },
};

List<string> extra;
try {
    extra = p.Parse (args);
}
catch (OptionException e) {
    Console.Write ("greet: ");
    Console.WriteLine (e.Message);
    Console.WriteLine ("Try `greet --help' for more information.");
    return;
}
Share:
12,231
Wesley Porter
Author by

Wesley Porter

Updated on June 04, 2022

Comments

  • Wesley Porter
    Wesley Porter about 2 years

    I'm quite familiar with command-line arguments and how to use them, but I have never dealt with options (or flags) before. I refer to something like the following:

    $ sort -f -s -u letters.txt
    

    In the bash script example above, we have 3 options or flags, followed by regular arguments. I want to do something similar in a C# application. What is the best way to handle command-line options where the arguments could be given in the following form?

    $ prog [-options] [args...]