C#: Console App that Accepts Command-Line Arguments

When it comes to building command-line applications in C#, handling command-line arguments efficiently is crucial. Command-line arguments allow users to pass inputs to the application at runtime, making the application more versatile and powerful. In this article, we’ll look at how to create a C# console application that accepts command-line arguments.

Accept Arguments in C# Console App

C# provides the args parameter in the Main method, which allows us to access command-line arguments passed to the application. Each argument is represented as a string in the args array.

Here’s how the Main method looks:

class Program
{
    static void Main(string[] args)
    {
        // Handle command-line arguments here
    }
}

Now, let’s see how we can access and process multiple command-line arguments:

class Program
{
    static void Main(string[] args)
    {
        // Check if any arguments are passed
        if (args.Length == 0)
        {
            Console.WriteLine("No arguments provided.");
        }
        else
        {
            // Iterate through each argument
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine($"Argument {i + 1}: {args[i]}");
            }
        }
    }
}

In the above code:

  • We check if any arguments are passed using args.Length == 0.
  • If arguments are provided, we iterate through each argument using a for loop and print them to the console along with their index.

Parse C# Console Arguments into Dictionary

Parsing command-line arguments into a dictionary allows for more efficient access to the arguments that are passed into the application. This is especially helpful when dealing with named arguments or key/value pairs.

Here’s an example of how to parse command-line arguments into a C# dictionary, supporting both named arguments and key/value pairs delimited by = character.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        var arguments = ParseArguments(args);

        // Check if 'help' argument is passed and output help string
        // If Zero arguments are passed in then output help string
        if (arguments.Count == 0 || arguments.ContainsKey("--help"))
        {
            PrintHelp();
            return; // Exit the application
        }

        // Example: Check if a specific argument is defined
        if (arguments.ContainsKey("--verbose"))
        {
            Console.WriteLine("Verbose mode enabled.");
        }

        // Example: Retrieve the value of a named argument
        if (arguments.TryGetValue("--output", out string outputValue))
        {
            Console.WriteLine($"Output file: {outputValue}");
        }
    }

    static Dictionary<string, string> ParseArguments(string[] args)
    {
        var arguments = new Dictionary<string, string>();

        foreach (var arg in args)
        {
            // Split the argument by '=' to handle key/value pairs
            string[] parts = arg.Split('=');

            // Check if the argument is in the format "key=value"
            if (parts.Length == 2)
            {
                arguments[parts[0]] = parts[1];
            }
            // If not, assume it's just a named argument without a value
            else
            {
                arguments[arg] = null;
            }
        }

        return arguments;
    }

    static void PrintHelp()
    {
        Console.WriteLine("Help:");
        Console.WriteLine("------");
        Console.WriteLine("Usage: CommandLineApp [options]");
        Console.WriteLine();
        Console.WriteLine("Options:");
        Console.WriteLine("  --help             Display this help message");
        Console.WriteLine("  --verbose          Enable verbose mode");
        Console.WriteLine("  --output=<file>    Specify output file");
    }
}

In this example:

  • Before checking for any other arguments, we first check if the --help argument is passed in.
  • If --help argument is passed or zero arguments are passed, the PrintHelp method is called to display the help message, and the application exits.
  • If --help argument is not found, the application proceeds with checking and processing other arguments.
  • If --output argument is found, the value of it is parsed out as any following the = character delimiter.