Adding “--help” parameter to C# console application

大憨熊 提交于 2019-12-04 15:00:29

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

David Arno

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 == "/?";
}

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.

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();
        }
    }

}

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!