Adding "--help" parameter to C# console application

17,181

Solution 1

A C# snippet for processing the command line across multiple cultures is...

        string[] args = Environment.GetCommandLineArgs();
        if (args.Length == 2)
        {
            if (args[1].ToLower(CultureInfo.InvariantCulture).IndexOf("help", System.StringComparison.Ordinal) >= 0)
            {
                // give help
            }
        }

The detection logic can be combined with "?" or "/?" or any other combination that covers all expected cases.

NOTE: when you get the arguments from the Environment, arg[0] is populated by the loader. The first 'user' argument is in arg[1].

Solution 2

With *nix commands, it's common to obtain help either via -h or --help. Many windows commands will offer help with /?. So it's not bad practice to do something like:

public static void Main(string[] args)
{
    if (args.Length == 1 && HelpRequired(args[0]))
    {
        DisplayHelp();
    }
    else
    {
        ...
    }
}

private static bool HelpRequired(string param)
{
    return param == "-h" || param == "--help" || param == "/?";
}

Solution 3

I use an intersection over a small collection of help commands. If I constrain myself tightly to your question; it winds up looking like this:

static bool ShowHelpRequired(IEnumerable<string> args)
{
    return args.Select(s => s.ToLowerInvariant())
        .Intersect(new[] { "help", "/?", "--help", "-help", "-h" }).Any();
}

Broadening the scope (just a little); I wind up with a method called ParseArgs that returns a boolean that is true if either parsing failed or help is required. This method also has an out parameter that stores parsed program parameters.

    /// <summary>
    /// Parses the arguments; sets the params struct.
    /// </summary>
    /// <param name="argv">The argv.</param>
    /// <param name="paramStruct">The parameter structure.</param>
    /// <returns>true if <see cref="ShowHelp"/> needed.</returns>
    static bool ParseArgs(IEnumerable<string> argv, out ParamStruct paramStruct)
    {
        paramStruct = new ParamStruct();

        try { /* TODO: parse the arguments and set struct fields */ }
        catch { return false; }

        return argv.Select(s => s.ToLowerInvariant()).Intersect(new[] { "help", "/?", "--help", "-help", "-h" }).Any();
    }

This makes things very convenient in the main and allows for good separation between ShowHelp and ParseArgs.

    if (!ParseArgs(argv, out parameters))
    {
        ShowHelp();

        return;
    }

Notes

  • Instead of having ParseArgs in Main one variation is to place the ParseArgs method into parameters struct as a static method.
  • The catch should only catch parsing exceptions; code does not reflect this.
Share:
17,181
user2450099
Author by

user2450099

Updated on June 04, 2022

Comments

  • user2450099
    user2450099 almost 2 years

    Almost all the .exe's I use via command line have a help function that gets called by the "--help" command.

    How do I implement this in C#? Is it as simple as checking whether or not the parameter in args[] is the string "--help"??

    • David Arno
      David Arno over 10 years
      Yes, it is as simple as that.
    • Admin
      Admin almost 9 years
      Why don't you use NDesk for this?
  • user2450099
    user2450099 over 10 years
    Thanks for providing a cross culture approach. I haven't checked whether the code compiles or not, however, but it looks good.
  • Gayot Fow
    Gayot Fow over 10 years
    I compiled it on both 4 and 4.5
  • David Arno
    David Arno almost 9 years
    @Christoph, nice edit there. Not sure how that = rather than == survived not being spotted for nearly two years! :)
  • Christoph Brückmann
    Christoph Brückmann almost 9 years
    No idea, probably because you have to edit at least 6 characters. But I "hacked" it by adding static to the method too. ;)
  • David Arno
    David Arno almost 9 years
    @ChristophBrückmann, ah, that makes sense. I just assumed the static was a code improvement on your part, not a "hack" as I forgot about the 6 char limit. Thanks for both fixes anyway :)
  • ScottWelker
    ScottWelker over 5 years
    @David Arno, I'd argue Christoph Bruckmann's edit is both code improvement and a trick to overcome the limit. The method doesn't require an instance. Making it static makes that clear. Although, this is a simplistic example and I wince just a bit at the method not being public - fine in this case ;)