DEV Community

Daniel Leinweber
Daniel Leinweber

Posted on

Parse CLI arguments in .NET

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"
                }
            )
        };
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)