3

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"??

Gayot Fow
  • 8,710
  • 1
  • 35
  • 48
user2450099
  • 375
  • 3
  • 7
  • 16

6 Answers6

22

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 == "/?";
}
Christoph Brückmann
  • 1,373
  • 1
  • 23
  • 41
David Arno
  • 42,717
  • 16
  • 86
  • 131
  • 1
    @Christoph, nice edit there. Not sure how that `=` rather than `==` survived not being spotted for nearly two years! :) – David Arno Jun 15 '15 at 10:37
  • No idea, probably because you have to edit at least 6 characters. But I "hacked" it by adding static to the method too. ;) – Christoph Brückmann Jun 15 '15 at 10:43
  • @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 :) – David Arno Jun 15 '15 at 10:49
  • @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 ;) – ScottWelker Jan 12 '19 at 12:18
9

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].

Gayot Fow
  • 8,710
  • 1
  • 35
  • 48
1

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.
dasm80x86
  • 363
  • 2
  • 7
0

Is it as simple as checking whether or not the parameter in args[] is the string "--help"??

Yes.

This is why different console programs sometimes have a different convention for how to get at the help information.

Servy
  • 202,030
  • 26
  • 332
  • 449
0

Yes. AFAIK, same as compring the arguments and displaying some strings on the screen.

static void Main( string[] args )
{
    if(  args != null && args.Length == 1 )
    {
        if( args[0].ToLower() == "help" )
        {
             ShowHelpHere();
        }
    }

}
Krishna
  • 1
  • 3
0

You can use the CommandLineParser nugget package. Then you can create an Options class, all metadata to provide help and validation. Pretty amazing and simple to implement.