Note You can check other posts on my personal website: https://hbolajraf.net
In this guide, we will explore how to build a Command-Line Interface (CLI) application using the System.CommandLine library in C# and .NET. System.CommandLine simplifies the process of creating robust and feature-rich command-line interfaces for your applications.
Before getting started, make sure you have the following installed:
dotnet new console -n MyCommandLineApp cd MyCommandLineApp
dotnet add package System.CommandLine --version 2.0.0-beta1.21308.1
In your Program.cs, define the command-line options using System.CommandLine:
using System.CommandLine; using System.CommandLine.Invocation; class Program { static int Main(string[] args) { var rootCommand = new RootCommand { new Option("--number", "An integer option"), new Option ("--flag", "A boolean option"), new Argument ("input", "A required input argument") }; rootCommand.Handler = CommandHandler.Create ((number, flag, input) => { // Your application logic goes here Console.WriteLine($"Number: {number}"); Console.WriteLine($"Flag: {flag}"); Console.WriteLine($"Input: {input}"); }); return rootCommand.Invoke(args); } }
dotnet run -- --number 42 --flag true "Hello, CLI!"
Replace the values with your own and see the output.
Add descriptions to your options and arguments for better help text:
var rootCommand = new RootCommand { new Option("--number", "An integer option"), new Option ("--flag", "A boolean option"), new Argument ("input", "A required input argument") }; rootCommand.Description = "A simple CLI app"; rootCommand.Handler = CommandHandler.Create ((number, flag, input) => { Console.WriteLine($"Number: {number}"); Console.WriteLine($"Flag: {flag}"); Console.WriteLine($"Input: {input}"); });
You have successfully created a basic Command-Line Interface (CLI) application using the System.CommandLine library in C# and .NET. Customize and extend the application based on your specific requirements.
For more information, refer to the official documentation: System.CommandLine GitHub
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3