Every console application I write needs some kind of command line arguments from user, and once the number of argument is larger than one the code to handle it becomes complex and built out of the same logical components (for each of my option find the command line argument, parse it and assign it.
If the arguments are not valid, write to console the allowed values
I decided to search for a good framework for it and i found NDesk.Options it suppose out of the box
- String & Boolean parameters
- Aliases for same parameter
- Automatic string that describe allowed values (including your description)
example of code to parse command line:
public class ProgramArguments {
public string PlatformXMLFileLocation { get; set; }
public string XMLOutputFileLocation { get; set; }
public bool Silent { get; set; }
public string[] ArgsToParse { get; set; }
private OptionSet Options = null;
public ProgramArguments() { }
public ProgramArguments(string[] args) : this() {
ArgsToParse = (string[])args.Clone();
ParseArgs();
}
public void ParseArgs() {
Options = new OptionSet() {
{ "i|input=", "Path of the input platform XML file", v => PlatformXMLFileLocation = v },
{ "o|output=", "Path of the output XML to represet errors", v => XMLOutputFileLocation = v },
{ "s|silent", "Run as silent", v => Silent = v!=null }
};
Options.Parse(ArgsToParse);
}
public void WriteOptionDescriptions(TextWriter o) {
Options.WriteOptionDescriptions(o);
}
public bool IsValid() {
return !string.IsNullOrEmpty(PlatformXMLFileLocation);
}
}
I am accepting:
-i, --input=VALUE - Path of the input platform XML file
-o, --output=VALUE - Path of the output XML to represent errors
-s, –silent - Run as silent
Above was generated by running WriteOptionDescriptions provided by NDesk <Smile />
Enjoy
