I\'m looking for a getopt library for c#. So far I found a few (phpguru, XGetOptCS, getoptfordotnet) but these look more like unfinished attempts that only support a part of
A friend of mine suggested docopt.net, a command-line argument parsing library based on the docopt library for Node.JS. It is very simple to use, yet advanced and parses arguments based on the help string you write.
Here's some sample code:
using System;
using DocoptNet;
namespace MyProgram
{
static class Program
{
static void Main(string[] args)
{
// Usage string
string usage = @"This program does this thing.
Usage:
program set <something>
program do <something> [-o <optionalthing>]
program do <something> [somethingelse]";
try
{
var arguments = new Docopt().Apply(usage, args, version: "My program v0.1.0", exit: false);
foreach(var argument in arguments)
Console.WriteLine("{0} = {1}", argument.Key, argument.Value);
}
catch(Exception ex)
{
//Parser errors are thrown as exceptions.
Console.WriteLine(ex.Message);
}
}
}
}
You can find documentation for it (including its help message format) at both the first link and here.
Hope it helps someone!
For the record, NUnit includes a simple one-file command-line parser in src\ClientUtilities\util\CommandLineOptions.cs
(see example usage in ConsoleRunner.cs
and Runner.cs
located under src\ConsoleRunner\nunit-console
). The file itself does not include any licencing information, and a link to its "upstream" seems to be dead, so its legal status is uncertain.
The parser supports named flag parameters (like /verbose
), named parameters with values (like /filename:bar.txt
) and unnamed parameters, that is, much in style of how Windows Scripting Host interprets them. Options might be prefixed with /
, -
and --
.
For posterity:
CommandParser is another one with a BSD license
Here is something I wrote, it works rather nice, and has quite a lot of features for the tiny amount of code. It is not getopts however, but it may suit your needs.
Feel free to ask some questions.
It's not getopt, but you might try NConsoler. It uses attributes to define arguments and actions.
The Mono Project has (or rather had) one based on attributes, but last I checked it was marked as obsolete. But since it's open source, you might be able to pull the code out and use it yourself.