DEV Community

Daniel Leinweber
Daniel Leinweber

Posted on

2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay