I cannot tell you how many times I forgot the name of this project when looking for a command line parser, so I thought the best way to remember it is by writing a blog post on the subject.
The github repository for PowerArgs has excellent documentation, so I will simply cover a few of the basics here, just to get things started.
PowerArgs is available via Nuget using Install-Package PowerArgs.
With PowerArgs we can define a class for our command line arguments and using PowerArgs attribute we define required arguments, optional arguments, argument descriptions and many other options. One very useful options is ArgExistingFile which tells PowerArgs the argument is a filename and it should exist.
Let’s look at some simple code. This class acts as my command line arguments for a simple Csv to Xml file application
public class Arguments { [ArgRequired] [ArgExistingFile] [ArgDescription("The mapping file")] public string MappingFile { get; set; } [ArgRequired] [ArgExistingFile] [ArgDescription("The CSV file to convert")] public string CsvFile { get; set; } [ArgRequired] [ArgDescription("The output XML file")] public string XmlFile { get; set; } }
In our Main method we’d then having something like this
try { var arguments = Args.Parse<Arguments>(args); // use the arguments } catch (ArgException e) { Console.WriteLine(ArgUsage.GenerateUsageFromTemplate<Arguments>()); }
In the above, we parse the args using the Parse method which will ensure the ArgRequired properties are supplied and the files exist via ArgExistingFile. If any required arguments are missing an ArgException occurs and we use ArgUsage.GenerateUsageFromTemplate to output a list of the command line arguments expect, as well as description of the arguments and we can also list examples.
Go look at the github repository PowerArgs for further documentation.