CommandLineParser

NeoticTools.CommandLineParser

 

 

 

Contents

Introduction

NeoticTools.CommandLineParser is a .Net C# class library that simplifies command line string parsing and displaying command line usage text.  It is a simple to use standard parser for reuse in many applications.

 

Features

  • Command line switches are declared using attributes on application properties.

  • Aliases.

  • -, & / switch prefixes.

  • String, Boolean, Enum, and Integer switches.  

  • Extensible for other switch types.

  • Reports unused portions of command string.

  • Parses Win32 and Forms style command strings.

  • Help usage string generation.

  • Explicit set switches report string generation.

 

Code Example

 

  1. Declare application switches by adding attributes to application properties.

     

    The following code fragment declares application command line switches:

    • "Help" with aliases; "h", & "?".
    • "Source" with aliases; "s", & "input".

    Command switch prefixes may be -, --, or /.  So valid help switches are -h, --h, or /h.

     

  2. [CommandLineSwitch("help", "Show usage information", @"h", @"\?")]

    public bool Help

    {

       // insert get, set code here

    }

     

    [CommandLineSwitch("source", "Source directory to scan", "s", "input")]

    public string Source

    {

       // insert get, set code here

    }

     

  3. Create and instance of the parser & parse the command line

  4. CommandLineParser commandLineParser = new CommandLineParser(this.Options);

    commandLineParser.Parse(System.Environment.GetCommandLineArgs());

     

  5. Application code

  6. error = commandLineParser.UnmatchedSwitches.Length > 0;

    if (this.Options.Help == true || error == true)

    {

      Console.Write(commandLineParser.Usage);

    }

    if (error == false)

    {

      Console.Write(commandLineParser.ExplicitOptions);

      // application code here

    }

     

That is all there is too it.  Easy!

 

Command Switches

Boolean

Syntax

[-|/][switchName][:| ]<true|yes|false|no>

Value

Value is optional, if not given the switch is set to true.  

Examples

-Help

/Debug yes

-Debug:FALSE

 

String

Syntax

[-|/][switchName][:| ]<">[value]<">

Value

String value.  May be double quote (") delimited.

Examples

-Name Fred

-Name "Fred Smith"

-InputFile:c:\temp\myfile.txt"

 

Integer

Syntax

[-|/][switchName][:| ][value]

Examples

-Maximum 0

 

Enum

Syntax

[-|/][switchName][:| ][value]

Value

Enum value string.

Examples

-Maximum 0

 

SourceForge.net Logo

 

 

Last updated 30th June, 2005, Robert Smyth