c# – How to parse command line parameters in a console application and display help on them

Question:

You need to write a console application in C# so that when you enter the run -h command, help is displayed with a description of the commands.

static void Main(string[] args)
{
    string command = string.Empty;
    if (args.Length != 0)
    {
        switch (args[0])
        {
            case "-h": help();
            break;
        }
    }
}

private void run(string utilityName, string arguments)
{
    try
    {
        clearOutput();
        pr = new Process();
        pr.StartInfo.FileName = utilityName;
        pr.StartInfo.Arguments = arguments;
    }
    catch ()  {} // ошибки
}

public static help()
{
    Console.WriteLine("-h help");
}

Answer:

There is no need to parse command line arguments manually. What you write will almost certainly have limited functionality and a zoo of bugs. No need to reinvent the wheel.

If you need to work with arguments in a more convenient way than the provided string[] args in Main , Environment.CommandLine , or Environment.GetCommandLineArgs , then you can use one of the many NuGet command line parser packages. They will allow you to interpret arguments as names and values, convert value types, generate help, etc.

Any parser you find will produce argument-value pairs. There are differences in the supported syntax, argument types, API (declarative, imperative, neither fish nor fowl), but the basic functionality is the same for all.

CommandLineParser is very popular, but I would warn against using it: the old adequate version of the library is abandoned and suffers from several bugs, the new version is rewritten in a completely stubborn style, unsupported, and there is no bright future in sight. List of popular libraries:

Some libraries expect you to have classes with attributes on properties, others expect a config built using the fluent interface, but in any case it will be easier to do than to reinvent the wheel, and you will get wider functionality: help generation, argument validation, strong typing, etc. . P.

Scroll to Top