Command Line with arguments

A sample .NET Core Console Application with arguments.

Example

Create a new console application.

$ dotnet new console -n CommandLineExample -o CommandLineExample

Install the package into your project.

.NET CLI

$ dotnet add package McMaster.Extensions.CommandLineUtils

Import the CommandLineUtils in the Program.cs

using Microsoft.Extensions.CommandLineUtils;

Create our application by creating a CommandLineApplication, and configure the default app Name, Description, and enable HelpOption.

The HelpOption will be used for trigger the help output, the syntax of the string is self-explanatory: use either "-?", "-h" or "–help" as a parameter.

To make the default action to do something, we define the OnExecute with simple output Hello World.

using Microsoft.Extensions.CommandLineUtils;
using System;

namespace CommandLineExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var app = new CommandLineApplication();
            app.Name = "ninja";
            app.Description = ".NET Core console app with argument parsing.";
            app.HelpOption("-?|-h|--help");

            app.OnExecute(() =>
            {
                Console.WriteLine("Hello World!");
                return 0;
            });

            app.Execute(args);
          }
    }
}

To create a command, use app.Command(name, Func<cmd>) to define the action and configure arguments in the command function.

To create command argument that accept for multiple option values, we can use CommandOptionType.MultipleValue while configure in command.Option.

In the sample code below, you can exclude multiple attack target. For example: $ ninja attack -e dragons -e animals

Commands

Generate the exe

If you really want to generate the exe then just run below command:

Debug Build

Release Build

Reference

Last updated

Was this helpful?