Why CommandLineParser Rocks

If you’ve ever hand-rolled parsing code for args[], you’ve inevitably landed in a nest of boilerplate, cryptic string checks, and error handling messes. Enter CommandLineParser—a clean, attribute-driven way to handle command-line options like a boss, with help generation, verbs, default values, and more, all baked in. You define a class with attributes, call the parser, and boom—typed, validated options galore with minimal code. (github.com)


Key Features (Cool, Not Boring)

  • Install via NuGet or Paket—works with .NET Framework, .NET Core, .NET Standard and Mono, no other dependencies required. (github.com)
  • Attribute-Based Mapping—use [Option] for named options (short/long), [Value] for positional args. Types supported include enums, nullable types, even System.Uri if it has a string constructor. (github.com)
  • Auto-Help & Version—default support for --help, --version, and even help [verb], without extra code. The library formats neat, readable help screens. (github.com)
  • Verbs—think Git commands like commit, push, pull. Each verb maps to a separate class with [Verb("name")], letting you build rich CLI tools with commands. (github.com)
  • Immutable Options Supported—for the functional crowd, it works with classes (or records) that lack setters; it’ll use constructors automatically. (github.com)
  • Async SupportWithParsedAsync and MapResult let you integrate smoothly with async workflows. (github.com)
  • Round-trip (Unparsing)—you can convert a parsed options instance back into a command-line string with Parser.Default.FormatCommandLine<T>(…). (github.com)

Quick-Start in Plain English

  1. Add the package:

    Install-Package CommandLineParser
  2. Define an options class:

    class Options {
        [Option('v', "verbose", Required = false, HelpText = "Enable verbose output.")]
        public bool Verbose { get; set; }
    
        [Value(0, MetaName = "input-file", HelpText = "File to process.", Required = true)]
        public string InputFile { get; set; }
    }
  3. In Main, parse and handle:

    Parser.Default.ParseArguments<Options>(args)
        .WithParsed(opts => RunApp(opts))
        .WithNotParsed(errs => HandleError(errs));

Done. That’s already a fully working, typed, help-enabled CLI.


Full C# Example (Techie But Totes Clear)

using System;
using CommandLine;

namespace MyCoolApp {
    class Program {
        public class Options {
            [Option('v', "verbose", Required = false, HelpText = "Enable verbose output.")]
            public bool Verbose { get; set; }

            [Option('o', "output", HelpText = "Output file path.", Default = "out.txt")]
            public string OutputFile { get; set; }

            [Value(0, MetaName = "input-file", HelpText = "The input file to process.", Required = true)]
            public string InputFile { get; set; }
        }

        static void Main(string[] args) {
            Parser.Default.ParseArguments<Options>(args)
                .WithParsed(Run)
                .WithNotParsed(errors => {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Oops! Something went wrong with parsing.");
                    Console.ResetColor();
                });
        }

        static void Run(Options opts) {
            if (opts.Verbose) {
                Console.WriteLine("[Verbose] Starting processing...");
                Console.WriteLine($"Reading from {opts.InputFile}, writing to {opts.OutputFile}");
            }

            // Simulated work
            Console.WriteLine($"Processing \"{opts.InputFile}\"...");
            // ... your logic here ...

            Console.WriteLine($"Done! Output saved to {opts.OutputFile}");
        }
    }
}

TL;DR Recap

  • Super minimal setup, no messy parsing code.
  • Built-in help/version, no extra scaffolding.
  • Git-style verbs, easy for multi-command tools.
  • Supports immutability, async, and un-parsing.
  • Well-documented and robust, with wiki and demos. (github.com, github.com, github.com, devblogs.microsoft.com)

Hope this helps you build CLI apps that are both polished and pleasant to maintain. Need a verb-based example or fancy help customization? Just say the word!

Use CommandLineParser and boost your app

Author

Lluis Franco

Publish Date

01 - 27 - 2024