Skip to content
This repository was archived by the owner on Jul 11, 2018. It is now read-only.

Quickstart

cosmo0 edited this page Nov 25, 2014 · 29 revisions

The instructions contained here will help you to use Command Line Parser Library in short time and with little effort.

Get it

Create a Console Application with Visual Studio and write this command at Package Manager Console:

PM> Install-Package CommandLineParser19

or

PM> Install-Package CommandLineParser20

If you prefer source inclusion, follow these steps to link a git submodule:

$ cd to/your/project/folder
$ mkdir lib && cd lib
$ git submodule add git://github.com/gsscoder/commandline.git commandline

You can even add the project as an external in SVN using the GitHub SVN "converter".

Use it

Now let your code open library's namespaces:

using CommandLine;
using CommandLine.Text; // if you want text formatting helpers (recommended)

Parsing target

Add a new class to your project. You could name it Options (or anything, really).

class Options
{
  [Option('i', "input", Required = true, HelpText = "Input file to read.")]
  public string InputFile { get; set; }

  [Option("length", DefaultValue = -1, HelpText = "The maximum number of bytes to process.")]
  public int MaximumLength { get; set; }

  [Option('v', null, HelpText = "Print details during execution.")]
  public bool Verbose { get; set; }

  [HelpOption]
  public string GetUsage()
  {
    // this without using CommandLine.Text
    //  or using HelpText.AutoBuild
    var usage = new StringBuilder();
    usage.AppendLine("Quickstart Application 1.0");
    usage.AppendLine("Read user manual for usage instructions...");
    return usage.ToString();
  }
}

An instance of this class will contain command line arguments read from the args[] array of the application's entry point.

Parsing rules are defined from various option attributes. This example allows the following commands, among others:

QuickstartApp -iMyData.bin --length=150
QuickstartApp -i MyData.bin -v
QuickstartApp -viMyData.bin --length 150

Parse command line

Now just invoke the parsing method in your Program.cs and you're done!

var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options))
{
    // consume Options instance properties
    if (options.Verbose)
    {
        Console.WriteLine(options.InputFile);
        Console.WriteLine(options.MaximumLength);
    }
    else
    {
        Console.WriteLine("working ...");
    }
}
Clone this wiki locally