Parse Command Line Argument using System.CommandLine – Guidelines

Today in this article we will see a technique of how to Parse Command Line Argument using System.CommandLine. We will use C# Console/Exe application using a simple and easy approach.

This approach can be used for regular .NET or .NET Core based applications.

Parsing a command-line argument has always been a need especially writing Console or exe or Batch application with multiple inputs.

One can easily create configuration and parsing around these inputs but it’s also important to do in a better way.

Today in this article, we will cover below aspects,

I am going to talk about a simple solution to this problem by using System.CommandLine. We will use the below simple example,

ConsoleApp1.exe --consumer-id 12312 --order-number 353453 --output-path C:\Test

We will also see how to configure Help command to get details about all the supported commands.

System.CommandLine is a NuGet library which provides a basic API for performing below three things.

  • Configuration of a command-line argument as root command using RootCommand

  • Parsing of command-line arguments into distinct constructs.

  • Invoking method/function using the CommandHandler.

Getting started

Create a Console C# .Net Core application using Command line or Visual Studio,

Lets see how to use this Nuget package,

Install Nuget package

Install the System.CommandLine Nuget package using CLI or Package Manager Console.

PM> Install-Package System.CommandLine -Version <VERSION>

Note: Please install latest version when available.

After installing the package please add below namespace,

using System.CommandLine;

using System.CommandLine.Invocation;

Configure Root Command

Create root command with required inputs.

For example– I have a requirement where, as a user I should be able to pass 3 below input to an exe.

Below are the 3 Input arguments which need to be passed to the Main method,

  • Consumer-id
  • Order-number
  • Output-path

To construct the root command please use below code ,

class Program
    {
        static int Main(string[] args)
        {
         
            var rootCommand = new RootCommand
            {
                new Option<string>(
                    "--consumer-id",
                    description: "Specify the Consumer id"),
                new Option<string>(
                    "--order-number",
                    "Specify Order number \n"),
                new Option<string>(
                    "--output-path",
                    "An option for file directory path where kafka meesage will be created.")
            };
     
            rootCommand.Description = "Console App to execute consumer commands for given Ids and generates reports with their Order Ids";
      }

Configure Root Command Handler

Below is how we can construct the root command handle which will let you execute the method with the given inputs provided in Main methods arg[] object.

class Program
    {
        static int Main(string[] args)
        {
         
           .
           .
           .
            rootCommand.Handler = CommandHandler.Create<string, string, string>(Execute);
            // Parse the incoming args and invoke the handler
            return rootCommand.InvokeAsync(args).Result;
        }

Implementation for Execute method as below,

static public void Execute(string consumerId, string orderNumber, string outputpath)
        {
            Console.WriteLine($"Input Consumer ID entered is: {consumerId}");
            Console.WriteLine($"Input Order Number entered is: {orderNumber}");
            Console.WriteLine($"Input Directory path entered is: {outputpath ?? "null"}");
        }

Executing the Console App or Exe application

You can execute the exe using any of the below option,

For ASP.NET Core 3.1 AND above

ConsoleApp1.exe --consumer-id 12312 --order-number 353453 --output-path C:\Test 

For ASP.NET Core 2.1 and less

dotnet run ConsoleApp1.exe --consumer-id 12312 --order-number 353453 --output-path C:\Test

Help command

Help command works out of the box using -h or -help commands out of the box and gives users all the details about the functionality.

Please use any of below commands,

-?   or    -h or  --help

Parse Command Line Argument using SystemCommandLine c net

That’s All. Enjoy Coding!

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

References :

Summary

Parsing a command-line argument is been always a challenge. There are many custom solutions around it already. Use System.CommandLine is a time saver and provides you many flexible options like configuring the input arguments, parsing the arguments, and letting you execute methods using these inputs.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *