28,79 €
Developers and system administrators often face challenges like inefficient workflows, complex system operations, and the growing demand for robust automation tools. CLI applications provide a powerful solution by enhancing flexibility, efficiency, and productivity in various environments. This book will guide you through mastering the development of robust command-line tools using .NET.
Written by a Microsoft Azure MVP, the book’s hands-on approach ensures practical experience with real-world projects. You’ll start with an overview of foundational principles, essential concepts, and best practices for CLI application development. From there, you’ll advance to creating interactive interfaces, integrating with external APIs and services, and implementing security measures to safeguard your applications. Each chapter will build progressively from basic to advanced topics.
Beyond development, you’ll learn how to enhance application quality through testing, package for efficient distribution, and deploy effectively. The book also teaches strategies to optimize performance to ensure your applications run efficiently under heavy usage.
By the end of this book, you’ll have gained a deep understanding of CLI application development with .NET to build modular, extensible, and easy-to-maintain applications.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 320
Veröffentlichungsjahr: 2025
Building CLI Applications with C# and .NET
A step-by-step guide to developing cross-platform CLI apps—from coding and testing to deployment
Tidjani Belmansour
Copyright © 2025 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
The author acknowledges the use of cutting-edge AI, such as ChatGPT, with the sole aim of enhancing the language and clarity within the book, thereby ensuring a smooth reading experience for readers. It’s important to note that the content itself has been crafted by the author and edited by a professional publishing team.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Kunal Sawant
Publishing Product Manager: Samriddhi Murarka
Book Project Manager: Prajakta Naik
Lead Editor: Kinnari Chohan
Technical Editor: Vidhisha Patidar
Copy Editor: Safis Editing
Proofreader: Kinnari Chohan
Indexer: Tejal Soni
Production Designer: Alishon Mendonca
Senior DevRel Marketing Executive: Sonia Chauhan
First published: February 2025
Production reference: 2170225
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-83588-274-0
www.packtpub.com
To my wife Lamia Rarrbo and to my daughter Camélia, for being the sunshine of my life. To my family for your love and support.
– Tidjani Belmansour
I remember when I first used Git.
I’d spent years working with Team Foundation Server (using TFVC), and I’d always done so through Visual Studio, so I’d become very used to the GUI. But Git felt like a different animal. I resolved to learn to use it from the Windows command line rather than relying on pointing and clicking.
It turned out to be a great decision. The CLI felt powerful and raw and exposed me to more of how Git worked. The simple request-response pattern was natural, and each command was self-contained. It meant that later, when I used GUI tools such as GitHub Desktop, I still understood what was happening under the hood. In subsequent jobs, no matter how unfamiliar the operating system, IDE, or development environment was, it always felt like I could drop back to the terminal to “talk to Git directly.”
Git was my gateway tool, but I quickly learned to love the simplicity of a CLI. It was straightforward when it needed to be, but for more power, I learned how to chain commands together or to use tools such as jq to parse JSON responses. For integration with my own software or scripts, well-written CLI tools meant I could make requests of APIs without having to construct exactly the right HTTP headers (is it text/jsonor application/json?).
When my career moved increasingly toward DevOps and developer processes, CLI tools became a core part of my practice, particularly when constructing CI/CD pipelines. It didn’t matter what tool I was using; it was easy to call a CLI tool to get the job done. CLIs were often cross-platform and consistent regardless of where you executed them. Switching from Jenkins to Azure Pipelines to GitHub Actions was not a big deal. It involved the same commands – they were just called from a different orchestrator.
Over time, I’ve come to love CLI tools for their simplicity, power, and directness. It brings me great joy when I see a CLI option alongside an API or GUI. It’s just another way to work with the software I use every day.
Applications and websites are frequently written with beautiful user interfaces, and these interfaces are important. But I think we’d be well served if more developers thought about – and built – the CLI as a first-class interface.
Damian Brady
Staff Developer Advocate, GitHub
Formerly DevOps Advocate at Microsoft
Tidjani Belmansour is an expert in developing and architecting solutions on the Microsoft Azure platform, particularly in .NET, with over 21 years of experience. His passion for development began early—he wrote his first program in QuickBasic at the age of eight and has never stopped since. He is currently the Director of the Azure Centre of Excellence at Cofomo, where he collaborates with organizations of all sizes, across both public and private sectors, and on projects around the globe.
Since 2019, Tidjani has been recognized as a Microsoft Azure MVP. He is also the co-host of the Azure Quebec Community, a trainer, a blogger, and an international speaker. Tidjani holds a BSc in Computer Science and a Ph.D. in Engineering.
This book is dedicated to my wife, Lamia, and my daughter, Camélia, for bringing light into my life and for being my source of support and inspiration. I love you both more than words can express.
To my family: my mother, Fatiha; my sister, Lamia; my second mom, Nacera; my sisters-in-law, Assia and Meriem; my brothers-in-law, Karim and Jordan; and my nephews, Zaki and Yani.
And to the memory of my father, Omar; my second father, Nasseradine; and my brother, Mounir.
Mabrouk Mahdhi is a software engineer, Microsoft MVP, and the founder of CodeCampsis, a consulting firm specializing in innovative IT solutions and .NET technologies. With a passion for technology and a commitment to sharing knowledge, Mabrouk is also a book author and an accomplished speaker, inspiring and educating audiences on a global scale.
To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:
https://packt.link/BuildNETCLI
In this part, you will get an overview of command-line interface (CLI) applications and understand their importance in modern software development. In addition, you will learn about setting up an efficient development environment for CLI programming, including essential tools and frameworks. Finally, you will explore the basic concepts of console applications in .NET, providing you with a solid foundation for creating powerful CLI tools.
This part has the following chapters:
Chapter 1, Introduction to CLI ApplicationsChapter 2, Setting Up the Development EnvironmentChapter 3, Basic Concepts of Console Applications in .NETIn the realm of computing, command-line interface (CLI) applications exemplify the enduring power and efficiency of text-based user interfaces. Unlike their graphical counterparts, CLI applications offer a streamlined, no-frills approach to interacting with software, allowing users to execute commands, manipulate files, and perform a myriad of tasks right from the terminal, or automate them so these tasks do not require user interaction at all!
In this chapter, we will cover the following topics:
An IT professional’s typical dayWhat CLI applications are, what their benefits are, and when to use themPopular CLI applicationsIt’s a beautiful Monday morning. Today, my team and I are starting a new project.
The project is to build a web application using ASP.NET with Entity Framework as an object-relational mapper (ORM), NuGet for managing dependencies, Git as a code versioning system, and, since the application is to be deployed on Azure, Bicep as an infrastructure scripting language.
A few years ago, I would have used GUI applications for this, such as the full-fledged Visual Studio, GitHub Desktop, or GitKraken, and the Azure portal.
Today, I doing most of my work in Visual Studio Code and its integrated terminal.
So, I use commands such as mkdir to create my project directory, cd to position myself into this directory, dotnet new to create my project, git init to initialize the Git repository, dotnet add package to add NuGet packages as dependencies to my project, dotnet ef dbcontext scaffold to generate a database context and all the entity type classes for my database, dotnet build to compile my application, and dotnet run to run it. When comes the time to deploy my application to Azure, I use commands such as az login to log into my Azure account, az account set to position myself onto the appropriate subscription, and finally, az deployment group create to deploy my Azure infrastructure as declared in my Bicep script.
When I realized that, I paused to pay careful attention to the situation. Wow, CLI applications are everywhere! They are truly part of our daily operations, no matter the role we play in an IT team.
I wondered how I missed that… then it hit me. This might be because CLI applications are a bit shy (they have no flashy UIs), and for that reason, we may not always notice them, so let me tell you about some common ones:
If you are a developer, you have certainly used the .NET CLI (dotnet), the Node.js CLI (node), the npm package manager (npm), the Angular CLI (ng), Python (python), Git (git), Docker (docker), Kubernetes (kubectl), and many more.If you are a DevOps engineer, you may be using Git (git), GitHub (gh), Azure DevOps (azdevops), Docker (docker), Kubernetes (kubectl), Ansible (ansible), and so on.If you are a system administrator, you may be regularly using package managers on various operating systems, such as apt on Linux, brew on macOS, or even choco or winget on Windows. You also most likely use shells, automation, and configuration tools such as PowerShell or Bash.If you are a cloud administrator or architect, you may be using the Azure CLI (az), the AWS CLI (aws), Terraform (terraform), or Bicep (bicep), among others.If you are a data scientist, you might be using Python (python), R (R), Pandas (pandas), SQL (sql), or Jupyter Notebooks (jupyter notebook).If you are a video or audio producer, a content creator, or simply a multimedia enthusiast, you are probably using FFmpeg (yes, it is a CLI application) to manipulate, convert, and analyze media files.And the list goes on and on…Then, I started wondering why this happened. How come we switched from those beautiful UIs with their shiny colors and animations, inviting us to do all sorts of tasks and activities, to the blinking cursor inside of that terminal that is waiting for us to tell it what to do? This might seem like a big leap backward, right?
I know I struggled with that feeling until I figured out why CLI applications are so great! Sure, they make us look cool and smart in front of our Muggle friends and relatives. But it’s not about that. Okay… not only about that. Because, when we are alone working on our project, there are not many people to impress.
So…
Because they improve our productivity by keeping us focused on the task at hand.
You see, when we switch contexts between different applications, the chances are that we lose sight of what we were doing and get derailed from our task by some other unrelated activity.
By relying on CLI applications, all the commands that we type and execute happen to be within the same terminal, so we have a better chance of staying focused on what we are doing, thus achieving more.
That is the question. And the answer is quite simple: you don’t have to choose. In some scenarios, CLI applications make perfect sense, while in others they make no sense. Imagine using Microsoft Teams, Slack, or any tool of the Adobe Creative Suite. Would it make sense to interact with these applications as CLI applications? Of course not! (unless it is for installing and configuring them).
So, the point here is that you become aware of the power of CLI applications, and you start taking advantage of them in your everyday workflow. They are not meant to replace those outstanding GUI applications.
As my wife, Lamia Rarrbo (who is an executive coach) says: “This is not an or situation but rather an and situation.”
Let me tell you a true story. A few years ago, one of my customers asked me to come up with a solution to build workstation configuration profiles for different roles within their company.
This is nothing new, you may say, and you are exactly right!
So, what makes this situation worth mentioning? What makes it special?
For many years, this used to be achieved using customized OS images, depending on the role you have in the organization. However, this comes at a cost:
The cost of storage: These images tend to be large and hence require a lot of disk space to store them.The cost of OS updates: When a new OS version is introduced, the IT department must recreate all images.The cost of tools updates: When new versions of the tools utilized by the various profiles are introduced, the IT department must recreate the impacted images.The cost of frustration: Since computers are configured using these images, and because this activity is solely performed by the IT department, it causes frustrations at both ends. First, users accuse the IT department of being slow at providing them with their new machine (“3 weeks to configure a new laptop?! You gotta be kidding me!”. We have all heard this at some point, right?). Second, the IT people have to configure these computers in addition to their other tasks.The solution I proposed is to leverage CLI applications to provide users with more autonomy while ensuring that the IT department still has control over what is deployed on the workstations.
So, I built configuration profiles for each role as a PowerShell script. This script relies on Chocolatey (and, later, on WinGet) to install all the necessary tools for a given user role. These scripts were stored on a file share that users had access to according to their role (so, for example, if you are an analyst, you don’t have access to the developer profile, and so on).
This solution provided multiple advantages:
The IT department now only installs the OS, configures the user account, and hand the workstation to the userThe user can now navigate to the file share and start the installation of their software based on their profileThe IT department can update the configuration profiles, or provide new ones, without having an impact on the users and without making them waitHence, by leveraging CLI tools, we were able to automate workstation configuration in a personalized manner, according to users’ profiles. Imagine how tedious this would have been if we had to install each and every application through its GUI assistant!
By relying on CLI tools, we were able to improve both the IT department’s productivity and users’ satisfaction.
Why is the preceding story interesting?
It’s not because of the use of PowerShell, WinGet, or Chocolatey. These are clearly CLI tools.
It is because we designed a way to install software from the command line without involving any GUI. This means that even if we are installing graphical applications (such as the Microsoft Office suite, internet browsers, and the Adobe suite), we are doing so by relying on their own CLI tools.
Yes, these graphical applications provide a CLI tool allowing us to install (and sometimes also configure) these applications.
A quick Google search and I found that there are even CLI applications for ChatGPT! Can you believe that?!
You can check out some of them at https://github.com/kardolus/chatgpt-cliand https://github.com/marcolardera/chatgpt-cli.
I am telling you: CLI applications are truly everywhere, and once you start caring about them, you start noticing how much they are part of your day!
If you work in IT, you have most likely already used at least one CLI application of some sort (and the chances are that you use many of them!), and you may even be using it on a daily basis.
I am sure that, by now, you have understood the value of CLI applications and the role they play in your everyday job.
In this book, we will explore every aspect of building our very own CLI applications, that serve our needs and those of our users and customers.
Feeling excited? Then, grab your keyboard, fire up your terminal, and let’s start coding!
We have only scratched the surface of what CLI applications can do and why they’re an essential tool in today’s tech landscape. I want this book to be your roadmap and your guide in this exciting journey.
Oh, and by the way, do not simply read this book, experience it!
Now, turn this page, and let’s continue our journey together. The world of CLI applications awaits you!
Enjoy the journey.
Throughout this book, we’ll build (and incrementally improve) a CLI application using .NET. We are going to start by setting up our development environment, which means installing the necessary tools to get started building CLI applications.
To reinforce and consolidate your learning, thereby getting the most out of this book, I strongly recommend that you practice the demos I’ll be showing you and complete the suggested exercises in the Your turn! sections at the end of each chapter. To do that, you’ll need to have your development environment set up and properly configured.
More specifically, in this chapter, we’re going to do the following:
Install Visual Studio CodeInstall the required extensionsInstall the .NET SDKInstall and configure GitThe code for this book can be found at https://github.com/PacktPublishing/Building-CLI-Applications-with-C-Sharp-and-.NET. The code for each chapter will be available in chapter-wise folders and will be mentioned in the Technical requirements section at the beginning of each chapter.
Note
There will be no code samples for this chapter, as we’ll be focusing on installing the necessary tools and getting your development environment ready. Please also note that all the required tools are available to you free of charge.
Throughout this book, I’ll be using a Windows 11 development machine. If you’re running on Linux or macOS, there should not be any major differences, apart from the installation of the tools, which I’ll highlight when needed throughout this chapter.
Even though .NET applications can be developed using various code editors and Integrated Development Environments (IDEs), we’ll be relying on Visual Studio Code.
Visual Studio Code is an open source, free-of-charge, cross-platform, powerful code editor from Microsoft that can be used to develop applications in numerous technologies (including .NET). Its true power comes from the wide variety of extensions, from Microsoft, third-party editors, and the community, that can be added to it to extend its capabilities and make it a code editor like no other. In my humble opinion, with all the possibilities that the extensions marketplace provides, Visual Studio Code is blurring the line that separates a “simple” code editor from a complete and powerful IDE.
My number one reason for choosing Visual Studio Code is that, by being cross-platform, its usage is the same whether you’re running on Windows, Linux, or macOS. Hence, even though I’ll be running on Windows, you’ll have no problem following along with me if you’re running on a different platform, and this is a huge advantage!
To download and install Visual Studio Code, the easiest method is to visit the https://code.visualstudio.com/ website and download it from there.
Figure 2.1 – Downloading Visual Studio Code for Windows
Important note
The Download for… link on the website should adapt to the platform you’re visiting the website from. In other words, if your computer is running Linux, the link should state Download for Linux. If not, click the drop-down symbol to the right of the download link to reveal other options.
Once the download is complete, head over to your downloads folder and double-click on the installer file. This will start the installation process. After you select Next and Finish, accepting the default values, you’ll have Visual Studio Code installed on your development workstation!
On the Select Additional Tasks screen of the installation wizard, I recommend that you check the two highlighted checkboxes in the following figure. These checkboxes will help you to open Visual Studio Code from the context of the current file/folder. I find this to be extremely useful.
Figure 2.2 – “Open with Code” checkboxes
Our code editor is now installed and ready to be used. However, the true power of Visual Studio Code lies in its extensions. They make the development process smooth and easy, while also improving the developer’s productivity.
At its essence, an extension is a software package that adds new features, functionality, or customizations to the Visual Studio Code editor.
Let’s install some extensions!
In this section, we’ll install some extensions that I highly recommend.
Feel free to install additional extensions as well. (Drop me a line on social media to let me know which other extensions you installed and why you like them. I’m always keen to learn new things 😊.)
The extensions I would recommend for this book are as follows:
C#: This extension from Microsoft is a no-brainer if you want to enable C# support in Visual Studio Code. It provides language support (including syntax highlighting and IntelliSense), debugging capabilities, and code completion.C# Dev Kit: This extension from Microsoft provides the Solution Explorer and Test Explorer experiences of the full-fledged Visual Studio in Visual Studio Code. If you’re migrating from Visual Studio to Visual Studio Code, or if you are still using both, this extension will provide you with a similar experience in both environments.IntelliCode for C# Dev Kit: This AI-powered extension provides whole-line completion, ranked IntelliSense suggestions, and personalized insights based on your code base.GitLens: This extension by GitKraken supercharges your Git experience within Visual Studio Code by providing features such as Git blame annotations, code navigation, and commit graph navigation. It greatly improves your Git productivity.Important note
If you’re using extensions for AI assistants, such as GitHub Copilot, in Visual Studio Code, you may be presented with a warning message stating that IntelliSense will not work if the AI assistant is enabled.
To add extensions to your Visual Studio Code environment, use the EXTENSIONS window by clicking the corresponding icon on the left-hand side of the Visual Studio Code interface:
Figure 2.3 – The EXTENSIONS window in Visual Studio Code
From there, you can search (and install) various extensions. You may also notice that Visual Studio Code will suggest extensions based on the type of application you’re developing. It’s up to you whether to install them. Just keep in mind that the more extensions you install, the more computer resources Visual Studio Code will consume. So, you may want to find a balance between the extensions you install and the performance hit you’re willing to accept.
Let’s install the C# Dev Kit extension next.
First, open the EXTENSIONS pane, as shown in Figure 2.3. Then, in the search bar, type C# Dev Kit. Multiple results might be returned, but the one we’re looking for should be at the very top. Make sure it is the right one (C# Dev Kit, developed by Microsoft) before clicking on it to select it and reveal its product page. Finally, click on the Install button below the name of the extension. The installation process should only take a few seconds.
Figure 2.4 – Installing the C# Dev Kit extension
Once installation is complete, and a project has been opened, the C# Dev Kit extension will add the SOLUTION EXPLORER