Parse CLI arguments in .NET
Daniel Leinweber
Posted on February 25, 2023
In my day-to-day job we needed a way to parse command line arguments in an easy and structured way.
So after some research I found the awesome NuGet-Package Command Line Parser Library. This package allows to define your options with Property-Attributes.
Example of a CommandLineOptions class
In this example class we define all options we want to parse as properties and create a static collection of Examples that will be displayed in the tools command line help.
public class CommandLineOptions
{
/// <summary>
/// e.g. yourapp.exe -d|--database "DatabaseName"
/// </summary>
[Option(
shortName: 'd',
longName: "database",
Required = true,
HelpText = "Name of the database to be used")]
public string DatabaseName { get; set; }
/// <summary>
/// e.g. yourapp.exe -l|--language "DE"
/// </summary>
[Option(
shortName: 'l',
longName: "language",
Required = false,
HelpText = "Country short key (EN|DE|IT|ES) for the report language")]
public string ReportLanguage { get; set; }
[Usage(ApplicationAlias = "yourapp.exe")]
public static IEnumerable<Example> Examples =>
new List<Example>()
{
new Example
(
"Use default settings",
new CommandLineOptions()
{
DatabaseName = "DatabaseName",
}
),
new Example
(
"Use custom report language",
new CommandLineOptions()
{
DatabaseName = "DatabaseName",
ReportLanguage = "DE"
}
)
};
}
Parse CommandLineOptions class
When your tool is executed you can than parse the passed arguments into the CommandLineOptions
class as follows.
static void Main(string[] args)
{
CommandLine.Parser.Default.ParseArguments<CommandLineOptions>(args)
.WithParsed(ExecuteWithOptions)
.WithNotParsed(HandleParseError);
}
static void ExecuteWithOptions(CommandLineOptions options)
{
// Handle options
}
static void HandleParseError(IEnumerable<Error> errors)
{
// Handle errors
}
💖 💪 🙅 🚩
Daniel Leinweber
Posted on February 25, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.