The instructions contained here will help you to use Command Line Parser Library in short time and with little effort. However to deepen every topic you need to read the rest of the user guide.

Download

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

PM> Install-Package CommandLine

If you prefer source inclusion (as I recommend), follow these steps:

cd to/your/project/folder
wget https://github.com/gsscoder/commandline/raw/master/src/libcmdline/CommandLine.cs

wget https://github.com/gsscoder/commandline/raw/master/src/libcmdline/CommandLineText.cs

If you download binary package from CodePlex, add a reference to CommandLine.dll using your preferred development environment. If you use a tool like NAnt, add the proper instruction in the build script file.

Let your code view library's public types.

C#:

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

Type For Parsing Target

Add a new class to your project. You could name it Options (or as you like more).

C#:

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

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

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

  [HelpOption]
  public string GetUsage()
  {
    // this without using CommandLine.Text
    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 args[] array of the application's entry point.
Parsing rules are defined from various [...Option...] attributes. In this example is allowed the following command line syntax (only some combinations of all possible).

Console:

QuickstartApp -iMyData.bin --lenght=150

QuickstartApp -i MyData.bin -v

QuickstartApp -viMyData.bin --lenght 150

Parse Command Line

Now the only thing left is to invoke the parsing method.

C#:

var options = new Options();
ICommandLineParser parser = new CommandLineParser();
if (parser.ParseArguments(args, options))
{
    // consume Options type properties
    if (options.Verbose)
    {
        Console.WriteLine(options.InputFile);
        Console.WriteLine(options.MaximumLenght);
    }
    else
        Console.WriteLine("working ...");
}

Last edited May 20, 2012 at 2:31 PM by gsscoder, version 43

Comments

laduran1 Oct 30, 2014 at 5:43 PM 
Massive number of typos and errors in the code examples. Misspellings, incorrect types, code won't compile. I was able to get it all working but simply having a sample project with each release that actually works with the release in use would be much more helpful than incorrect "documentation"

Still, nice attempt at making this simpler.

626 Oct 25, 2013 at 12:46 PM 
This line is incorrect:
PM> Install-Package CommandLine

Running this returns an error: Install-Package : Unable to find package 'CommandLine'.

It should be:
PM> Install-Package CommandLineParser

ajitpeter Aug 5, 2013 at 10:24 AM 
Wonderful library to make a console app more intuitive. For the working version of the examples visit the GitHub page. The examples shown in here does not work.

CMercs Mar 14, 2013 at 4:28 PM 
Here are some corrected examples with Length spelled correctly, char shortName as an actual Char, null shortName removed and most importantly the removed ICommandLineParser replaced with the new CommandLine.Parser. This would have saved me some time. Hope it saves you some.;

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

[Option('l', "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
var usage = new StringBuilder();
usage.AppendLine("Quickstart Application 1.0");
usage.AppendLine("Read user manual for usage instructions...");
return usage.ToString();
}
}

///Parse Command Line
Options options = new Options();
CommandLine.Parser parser = new Parser();
if (parser.ParseArguments(args, options))
{
// consume Options type properties
if (options.Verbose)
{
Console.WriteLine(options.InputFile);
Console.WriteLine(options.MaximumLenght);
}
else
Console.WriteLine("working ...");
}

jrummell Feb 6, 2013 at 1:05 PM 
The NuGet package is a actually CommandLineParser, right?

topry Nov 5, 2012 at 2:57 PM 
Very useful - thank you for providing this.

jonketo Jun 4, 2012 at 2:15 AM 
There are lots of error in the quickstart example. Please update.

gsscoder May 19, 2012 at 4:24 PM 
VB.NET (sample | template): https://github.com/gsscoder/commandline/blob/master/src/templates/VBNetTemplate/Program.vb

gsscoder May 14, 2012 at 8:28 PM 
This page is now updated to latest sources on github. Last versions of API lacks support for dressing target options instances defined with fields, use properties instead! (the author)

cmathis3 Oct 20, 2010 at 6:41 PM 
I modified this code to run in VB. Hope it helps someone!
<pre>

Imports CommandLine
Module Module1

Sub Main(ByVal args() As String)
Process(args)

End Sub

Sub Process(ByVal args As Array)

Dim settings As CommandLineParserSettings = New CommandLineParserSettings()
settings.CaseSensitive = False ' //don't care what case parms are entered
settings.HelpWriter = Console.Error ' // write help info to console

Dim envArgs As Array = Environment.GetCommandLineArgs() '// get command line parms from Env -includes program name
Dim envStr As String = Environment.CommandLine '// get the command line as a single string
Dim options As Options = New Options()

Dim parser As ICommandLineParser = New CommandLineParser(settings)
Try
Dim goodParse As Boolean = parser.ParseArguments(args, options)
If Not goodParse Then
Console.WriteLine("Parse Error !")
End If

Console.WriteLine("Command Line:" + envStr)
Console.WriteLine("Command Line Args:")
For Each str As String In args
Console.WriteLine(str)
Next

'// consume Options type fields
If (options.Verbose) Then
Console.WriteLine("Parsed Command Line Values:")
Console.WriteLine(options.InputFile)
Console.WriteLine(options.MaximumLength)
Console.WriteLine(options.maxToRead)
If (options.Items.Count > 0) Then
Console.WriteLine(" Unattached parms: " + options.Items.Count.ToString())
For Each it As String In options.Items
Console.WriteLine(" - " + it)
Next
End If
Else
Console.WriteLine("working ...")
End If
Catch ex As Exception
MsgBox("Error:" + ex.ToString())
End Try

Console.WriteLine("Press enter to End Program")
Console.ReadLine()

End Sub
End Module




Imports CommandLine
Imports CommandLine.Text
Imports System.Text
Imports System.Collections.Generic
Imports System.Collections
Class Options

<ValueList(GetType(List(Of String)))> _
Public Items As IList(Of String) = Nothing

<[Option]("i", "input", Required:=True, HelpText:="Input file to read.")> _
Public InputFile As String = Nothing

<[Option](Nothing, "length", HelpText:="The maximum number of bytes to process.")> _
Public MaximumLength As Integer = -1

<[Option]("m", "MaxToRead", HelpText:="Maximum Records To Read")> _
Public maxToRead As Long = -2
<[Option]("v", Nothing, HelpText:="Print details during execution.")> _
Public Verbose As Boolean = False

<HelpOption(HelpText:="Display this help screen.")> _
Public Function GetUsage() As String
Dim HelpText = New HelpText("Help Text")
HelpText.AddOptions(Me)
Dim usage = New StringBuilder()
usage.AppendLine("Quickstart Application 1.0")
usage.AppendLine("Read user manual for usage instructions...")
Return usage.ToString() & Convert.ToString(HelpText)
End Function
End Class
</pre>

gehho Aug 24, 2010 at 11:17 AM 
Cool! Looks like a very helpful library.

BTW: You misspelled the word "length" several times in this example ("lenght"), as well as "display" which you wrote as "dispaly"...

DanPhillips Jul 30, 2010 at 4:27 AM 
There's a complete sample in the src download, and there's a compiled version of that in the bin download.

LarsCorneliussen Feb 25, 2010 at 8:38 AM 
Just some things that would have helped me to get started...

1) GetUsage should defenitely use HelpText to show the auto-help generation ( I had to look into this to find it, since it was not documented and not in the sampleapp: http://sqlcecmd.codeplex.com/SourceControl/changeset/view/39540#362912)

2) Environment.Exit(-1) should be called if the parsing doesn't work

3) the console section could then also show the help-output

4) Consider using HeadingInfo and CopyrightInfo in the example