C# parsing Command Line arguments the easy way
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
3 comments:
nice!
First of all. Thanks very much for your useful post.
I just came across your blog and wanted to drop you a note telling you how impressed I was with the
information you have posted here.
Please let me introduce you some info related to this post and I hope that it is useful for community.
There is a good C# resource site, Have alook
http://CSharpTalk.com
Thanks again
Rahul
Very Simple Command Line Arguments Parser, it can be used as a foundation for your own application specific parameter presenter.
Post a Comment