Skip to content

Your first app with System.CommandLine

Jon Sequeira edited this page Aug 20, 2019 · 19 revisions

Building your first app with System.CommandLine

This walkthrough will show you how to get started using System.CommandLine to build a command line application.

Create a new console app

Open a new console and run the following commands:

> dotnet new console -o myApp
> cd myApp

Install the System.CommandLine.Experimental package

Nuget

Add some code

Open Program.cs. At the top, add a using directive:

using System.CommandLine;

Your Main method looks like this:

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");
}

Now, let's add a parser.

You'll need a few more using directives:

using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;

Now change your Main method to this:

static int Main(string[] args)
{
    // Create a root command with some options
    var rootCommand = new RootCommand
    {
        new Option(
            "--int-option",
            "An option whose argument is parsed as an int")
        {
            Argument = new Argument<int>(defaultValue: () => 42)
        },
        new Option(
            "--bool-option",
            "An option whose argument is parsed as a bool")
        {
            Argument = new Argument<bool>()
        },
        new Option(
            "--file-option",
            "An option whose argument is parsed as a FileInfo")
        {
            Argument = new Argument<FileInfo>()
        }
    };

    rootCommand.Description = "My sample app";

    rootCommand.Handler = CommandHandler.Create<int, bool, FileInfo>((intOption, boolOption, fileOption) =>
    {
        Console.WriteLine($"The value for --int-option is: {intOption}");
        Console.WriteLine($"The value for --bool-option is: {boolOption}");
        Console.WriteLine($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
    });

    // Parse the incoming args and invoke the handler
    return rootCommand.InvokeAsync(args).Result;
}

You're ready to run your program.

> dotnet run -- --int-option 123
The value for --int-option is: 123
The value for --bool-option is: False
The value for --file-option is: null

This program is equivalent to the one demonstrated in Your first app with System.CommandLine.DragonFruit.

To explore its features, take a look at Features: overview

You can’t perform that action at this time.