Using NDesk.Options for Command Line Parsing

Another snippet to remind future-me (and maybe future-you) how to use a nice command line parsing library I just discovered called NDesk.Options.

In this example, I created an object to hold the collection of command line options so they can be passed around the program. Then I created a builder object to take the array of string arguments from Main and parse them out into discrete settings.

NDesk.Options supports using lambdas to process each command line option so it makes it very easy to see which string option relates to which field.

Here’s a set of command line options for an application we’d like to set from the command line:


internal class CommandLineOptions 
{
	public string ProjectFilePath { get;set; }

	public string OutputFilePath { get; set; }

	public bool ShowHelp { get; set; }

	public AnalysisOption AnalysisOption { get; set; }
}


And here’s the super simple code to parse out arguments into properties in the object:


using NDesk.Options;

internal class CommandLineOptionsBuilder 
{
    public CommandLineOptions GetOptions(string[] args) 
	{
		CommandLineOptions options = new CommandLineOptions();

		var os = new OptionSet
		{
   			{ "project=",      	path => options.ProjectFilePath = path },
   			{ "output=",      	path => options.OutputFilePath = path },
   			{ "t|targets",  	t => options.AnalysisOption = AnalysisOption.Targets },
   			{ "i|items",  		i => options.AnalysisOption = AnalysisOption.Items },
   			{ "p|properties",  	i => options.AnalysisOption = AnalysisOption.Properties },
   			{ "h|?|help",   	help => options.ShowHelp = help != null },
		};
			
		os.Parse(args);

        return options;
    }
}