Move over old style command line processing, if you're using Mono and C# - check out the Mono.GetOptions class to process command line options via .NET Attributes. ( Sample code lifted from a post by Jonathan Pryor to the mono.general mailing list.)
The first step is to import the required assemblies in you code:
using System;
using System.Reflection;
using Mono.GetOptions;
Next we define some general meta-data for our application:
// Attributes visible in " --help"
[assembly: AssemblyTitle ("go.exe")]
[assembly: AssemblyVersion ("1.0.*")]
[assembly: AssemblyDescription ("Mono.GetOptions Sample Program")]
[assembly: AssemblyCopyright ("Public Domain")]
// This is text that goes after " [options]" in help output.
[assembly: Mono.UsageComplement ("")]
// Attributes visible in " -V"
[assembly: Mono.About("Insert About Text Here.")]
[assembly: Mono.Author ("Your name here")]
Almost there, now we define a class to hold our options.
class SampleOptions : Options
{
// Long option is the variable name ("--file"), short option is -f
[Option ("Write report to FILE", 'f')]
public string file;
// Long option is the variable name ("--quiet"), short option is -q
[Option ("don't print status messages to stdout", 'q')]
public bool quiet;
// Long option is as specified ("--use-int"), no short option
[Option ("Sample int option", "use-int")]
public int use_int;
public SampleOptions ()
{
base.ParsingMode = OptionsParsingMode.Both;
}
}
And finally, write a program to use it:
class TestApp
{
public static void Main (string[] args)
{
SampleOptions options = new SampleOptions ();
options.ProcessArgs (args);
Console.WriteLine ("Specified Program Options:");
Console.WriteLine ("\t file: {0}", options.file);
Console.WriteLine ("\t quiet: {0}", options.quiet);
Console.WriteLine ("\t use_int: {0}", options.use_int);
Console.WriteLine ("Remaining Program Options:");
foreach (string s in options.RemainingArguments) {
Console.WriteLine ("\t{0}", s);
}
}
}
Oh yeh, and don't forget to compile it:
mcs -r:Mono.GetOptions go.cs
And voila, no muss. And what does it look like?
[mark@localhost mark]$ mono go.exe --help
go.exe 1.0.1573.25851 - Public Domain
Mono.GetOptions Sample Program
Usage: go [options]
Options:
-f --file:PARAM Write report to FILE
-? --help Show this help list
-q --quiet don't print status messages to stdout
--usage Show usage syntax and exit
--use-int:PARAM Sample int option
--verbosegetoptions Show verbose parsing of options
-V --version Display version and licensing information
[mark@localhost mark]$ mono go.exe --V
go.exe 1.0.1573.25851 - Public Domain
Mono.GetOptions Sample Program
Insert About Text Here.
Authors:
Your name here
Specified Program Options:
file:
quiet: False
use_int: 0
Remaining Program Options:
links: digg this del.icio.us technorati reddit