Now we turn our attention to Program.cs
, making the changes needed to use the Niche.CommandLineProcessor) library to actually parse the arguments supplied by a user. One of the goals of the v3.0 release of the library was to make this as simple as possible.
The easiest approach is to let the Niche.CommandLineProcessor do all the heavy lifting on your behalf.
To begin, we have the usual declaration for Main
, followed by the creation of our logger. Note that the logger is not a part of the library.
Next, we create a processor to handle the arguments we’ve been supplied, inside a using clause so that it can tidy itself up when we’re finished with it.
When an error happens during parsing, we want to write those error messages to our logger as failures:
Errors can happen when a mandatory parameter is missing, when a value can’t be converted into the expected type, or when an exception is thrown.
Calling the error action is deferred until the processor is disposed at the end of the using block.
If the user requests help (by using the --help
or -h
options), we also want those messages to be written to our log.
Similarly to the way the error action is deferred, calling the help action is deferred until the processor is disposed at the end of the using block.
Both WithErrorAction()
and WithHelpAction()
allow you to cleanly inject your own handlers with the behavior you want/need for your application. For example, you could emulate msiexec
and display a dialog showing your parameter help, instead of logging those help messages to the console.
Lastly, we invoke the processor to parse the available arguments and to execute our application by calling MainImpl()
.
The Niche.CommandLineProcessor library takes care of these common cases:
- If the user requests parameter help (by specifying
--help
or-h
arguments), help will be shown, using the action supplied toWithHelpAction()
. - If anything goes wrong during parsing, the errors will be shown, using the action supplied to
WithErrorAction()
. - The method supplied to
Execute()
will be executed only if there are no errors and help has not been requested.
Comments
blog comments powered by Disqus