c sharp

How to Parse Command Line Arguments in C#

One way or another, you are going to come across an instance where you need to build a console-based applications. One of the most fundamental feature of CLI-based application is the use of parameters, arguments, or switches.

Arguments in a CLI app allow you to define the behavior and the functionality of the app. An example usage of CLI arguments is utility applications, automation scripts, and more.

In this guide, we will cover the various methods and techniques that you can use to parse the command line arguments in C#.

Array Indexing

The method where we can store the arguments in C# is using the string[] args array in the main function. Since the resulting value is an array, we can simply access the values that are stored in the array using the array indexing.

An example is as follows:

class Program
{
    static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            Console.WriteLine($"First Argument: {args[0]}");
        }
        else
        {
            Console.WriteLine("No arguments provided.");
        }
    }
}

In the given example, we start by checking if the length of the array is greater than 0 which means that the program received the arguments.

We then directly access the args array to get the command line arguments.

Foreach Loop

We can also take advantage of the foreach loop in LINQ to quickly iterate over all the arguments that are stored in the args array. This removes the need to know the number of arguments in the array.

class Program
{
    static void Main(string[] args)
    {
        foreach (var arg in args)
        {
            Console.WriteLine($"Argument: {arg}");
        }
    }
}

This provides an efficient way of handling all arguments, especially when you don’t know the exact number of arguments in advance.

CommandLineParser Library

When you are dealing a complex application that needs to parse and handle a wide variety of arguments, you need to go past a simple array iteration.

This is where the external libraries come into play. One of the libraries that you can use is the CommandLineParser lib.

Start by installing it in your project.

NuGet\Install-Package CommandLineParser -Version 2.9.1

Once installed, you can use it in your project as shown in the following example demonstration:

using System;
using CommandLine;

namespace QuickStart
{
    class Program
    {
        public class Options
        {
            [Option('v', "verbose", Required = false, HelpText = "Set output to verbose messages.")]
            public bool Verbose { get; set; }
        }

        static void Main(string[] args)
        {
            Parser.Default.ParseArguments<Options>(args)
                   .WithParsed<Options>(o =>
                   {
                       if (o.Verbose)
                       {
                           Console.WriteLine($"Verbose output enabled. Current Arguments: -v {o.Verbose}");
                           Console.WriteLine("Quick Start Example! App is in Verbose mode!");
                       }
                       else
                       {
                           Console.WriteLine($"Current Arguments: -v {o.Verbose}");
                           Console.WriteLine("Quick Start Example!");
                       }
                   });
        }
    }
}

In this case, the “Options” class is where we define the properties that we expect from the CLI arguments. We then use the “Option” attribute to map the properties to specific switches.

The role of the ParseArguments method is to parse the arguments and perform the required actions on the matching value.

Conclusion

In this tutorial, we covered the various methods that you can use to parse the CLI arguments in C# starting with the basic array indexing to external argument parsers.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list