Ookii.CommandLine

Ookii.CommandLine is a class library for .Net applications providing easy to use command line argument parsing.

Like many programming frameworks, .Net provides a process with the command line arguments supplied when the process was created as an array of strings. Many developers end up writing code to interpret these arguments, which is tedious and can be error prone. Ookii.CommandLine provides you with the functionality to quickly and easily parse the command line arguments, and store the results in a class so you can easily access them.

Requirements

Ookii.CommandLine requires the Microsoft .Net Framework 3.5 SP1. The included source code is intended for use in Visual Studio 2008. Ookii.CommandLine is also supported on Mono (tested on Mono 2.4.3).

Download

Download Ookii.CommandLine (binaries, source code, samples and documentation).

Documentation

General information is provided below. The complete Ookii.CommandLine class library documentation is available as well.

The primary functionality is provided by the Ookii.CommandLine.CommandLineParser<T> generic class. The type argument to this class specifies the class that will receive the values of the command line arguments.

Positional and named arguments

The Ookii.CommandLine library distinguishes two types of command line arguments: positional and named arguments.

Positional arguments are identified by the order in which they appear on the command line. For instance, if you invoke the Windows copy command with "copy file.ext c:\", both parameters are positional arguments, and their meaning is determined by the order. "file.ext" is the source, because it is the first positional argument, while "c:\" is the destination, because it is the second positional argument.

Positional arguments can be optional. An optional argument can be omitted from the command line, in which case it will have its default value. Note that you cannot have any required positional arguments following an optional argument, because in that case it is not possible to determine if the argument has been omitted.

Named arguments are identified by name, and are preceded by a special character to distinguish them from the positional arguments. On Windows, this character is typically a forward slash "/", while on Unix it's typically a dash "-". You can specify which character to use by setting the CommandLineParser<T>.NamedArgumentSwitch property. This property will default to "/" on Windows and to "-" on Unix operating systems (Unix is supported via Mono).

Named arguments can appear in any order, and are never required. A named argument can have a value which is specified after a colon following the attribute name, e.g. "/argument:value". Alternatively, a named attribute can simply have a meaning defined by its presence or absence. For example, many applications use /v to indicate you want verbose output, while the absence of that argument means you don't want verbose output. These kinds of arguments are created by the CommandLineParser<T> by using the Boolean type for the argument.

Arrays are supported for both named and positional arguments. For positional arguments, only the last argument may be an array, in which case all remaining positional arguments specified on the command line will be elements of this array. For named arguments with an array type, you can repeat the argument multiple times, e.g. "Program.exe /val:foo /val:bar" will set the "val" argument to an array containing { "foo", "bar" } if it's an array argument.

Programmer's guide

To use the Ookii.CommandLine library, you must create a class that specifies the various command line arguments, and that will receive the values of these arguments.

The parameters of the class's constructor will be used as the positional arguments. If the class has more than one constructor, you can indicate which constructor should be used by setting the CommandLineConstructorAttribute attribute on that constructor (to have multiple constructors but none marked with this attribute or multiple constructors with this attribute is an error). If you have only one public constructor, this attribute is not necessary.

To create an optional positional argument, apply the System.Runtime.InteropServices.OptionalAttribute attribute to the constructor parameter. To set the default value, apply the System.Runtime.InteropServices.DefaultParameterValueAttribute to the constructor parameter. In Visual Basic, you can use the Optional keyword and built-in syntax to specify the default value.

To create named parameters, add properties to the class and set the NamedCommandLineArgumentAttribute attribute on those properties. You can use this attribute to specify the name of the command line switch for the argument, and optionally the default value.

The type of the constructor parameter or property related to an argument determines the type of the argument. Ookii.CommandLine will use the System.ComponentModel.TypeConverter class to convert the text typed by the user to this type.

For named arguments that are Booleans, the presence of the argument determines the value. If it is present, the value will be true, and if it is not, the value will be false.

The following sample shows a simple command line arguments class that defines two positional arguments, one of which is optional, and one named argument.

C#:
class CommandLineArguments
{
    private string _arg1;
    private int _arg2;

    public CommandLineArguments(string arg1, [Optional, DefaultParameterValue(1)] int arg2)
    {
        _arg1 = arg1;
        _arg2 = arg2;
    }

    [NamedCommandLineArgument("arg3", DefaultValue = "foo")]
    public string Argument3 { get; set; }
}
Visual Basic:
Class CommandLineArguments
    Private _arg1 As String
    Private _arg2 As Integer
    Private _arg3 As String

    Public Sub New(ByVal arg1 As String, Optional ByVal arg2 As Integer = 1)
        _arg1 = arg1
        _arg2 = arg2
    End Sub

    <NamedCommandLineArgument("arg3", DefaultValue:="foo")> _
    Public Property Argument3() As String
        Get
            Return _arg3
        End Get
        Set(ByVal value As String)
            _arg3 = value
        End Set
    End Property
End Class

Once you have created this class, you create an instance of the CommandLineParser<T>, specifying that class in place of T. Call the Parse method to parse the command line arguments and receive the results.

C#:
static void Main(string[] args)
{
    CommandLineParser<CommandLineArguments> parser = new CommandLineParser<CommandLineArguments>();
    CommandLineArguments arguments = parser.Parse(args);
}
Visual Basic:
Sub Main(ByVal args() As String)
    Dim parser As New CommandLineParser(Of CommandLineArguments)
    Dim arguments As CommandLineArguments = parser.Parse(args)
End Sub

For more complete examples, demonstrating more of the features of the Ookii.CommandLine library, please check the source code of the included example applications. Also check the included class library documention for more information about the features of the Ookii.CommandLine library.

Generating usage text

In addition to parsing the command line arguments, Ookii.CommandLine can automatically generate help text about the usage of your application. This usage text will list all the command line arguments, as well as additional descriptions you can add. To retrieve this text, simply use the CommandLineParser<T>.Usage property. To customize certain aspects of the usage text, use the CommandLineParser<T>.GetCustomUsage method instead.

To add a description to a positional argument, apply the System.ComponentModel.DescriptionAttribute attribute to the constructor parameter. To add a description to a named argument, apply the System.ComponentModel.DescriptionAttribute attribute to the property.

You can also apply the System.ComponentModel.DescriptionAttribute to the class itself, in which case this text will be printed before the other usage information. All text will be properly line-wrapped on the word boundaries to fit on the console.

For example, the usage text of one of the included sample applications is as follows:

Sample command line application. The application parses the command line and
prints the results, but otherwise does nothing, and none of the arguments are
actually used for anything.

Usage: CommandLineSampleCS.exe [/?] [/id:Identifier] [/v] [/val:Values...]
   <source> <destination> [count=1]

       source : The source data.

  destination : The destination data.

        count : The operation count. This argument is optional, and the default
                value is 1.

           /? : Displays this help message.

          /id : Sets the operation ID. The default value is "default".

           /v : Print verbose information.

         /val : This is an example of an array argument, which can be repeated
                multiple times to set more than one value.