How do I print help for console apps?

Is there an idiomatic way to print out help for console apps? In Powershell, this is really simple, but I can't find a mention of it in MS Docs or the Yellow Book. Googling shows a number of people rolling their own approach over the years. Am I missing an 'official' or at least, best practice, way of printing help for a command line utility?

Posted Sep 12, 2020, 6:36 PM UTC

27
darinclark•

I think the Command Line Api package is what you want. https://github.com/dotnet/command-line-api

This is how I have used it.

using Computerizing.Common.Data.File;
using Computerizing.Common.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.CommandLine;
using System.CommandLine.Parsing;

namespace CSV_ToSql {
class Program {
    static int Main(string[] args) {
        Program instance = new Program();
        var rootCommand = new RootCommand("CSV To SQL");
        rootCommand.AddCommand(CommandLineOptions
            .CreateSchema(instance.InferSchema));
        rootCommand.AddCommand(CommandLineOptions
            .FromSchema(instance.FromSchema));
        return rootCommand.InvokeAsync(args).Result;          
    }
      
    int InferSchema(string input, string table, string schema, 
        bool updateschema, IEnumerable<string> nullvalues, 
        string output, string classname = null) {
        // Code
    return 0;
    }

    int FromSchema(string input, string table, string schema, 
        string output) {
        // Code
        return 0;
    }
}
}

using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Invocation;
namespace CSV_ToSql {
public class CommandLineOptions {

    public delegate int CreateSchemaHnd(string input, 
        string table, string schema, bool updateschema, 
        IEnumerable<string> nullvalues, string output, 
        string classname = null);
    public static Command CreateSchema(CreateSchemaHnd handler) {
        Command result = new Command("createschema", 
            "Pre-parse source file to build table Schema");

        result.AddValidator(s => {
            var updateOpt = s.Children["updateschema"];
            if (!s.Children.Contains("table") && updateOpt is null) {
                return "You must specify a table name if not updating an existing schema";
            }

            var schemaOpt = s.Children["schema"];
            if (updateOpt != null && schemaOpt is null) {
                return "You must specify a schema file to update.";
            }
            if (schemaOpt is null && !s.Children.Contains("output")) {
                return "You must specify an output file or schema file";
            }
            return null;
        });

	result.AddOption(new Option(new[] { "-i", "-input" },
            "File name for Source csv file") 
            { Argument = new Argument<string>() ,Required = true}
        );
        result.AddOption(new Option(new[] { "-t", "-table" },
	    "SQL Table Name. You can leave this blank if updating an existing Schema") 
            { Argument = new Argument<string>() }
	);
	result.AddOption(new Option(new[] { "-s", "-schema" },
	    "FileName for xml serialized Schema. If blank we won't save the schema")
            { Argument = new Argument<string>("fileName") }
	);
	result.AddOption(new Option(new[] { "-u", "-updateschema" },
	    "Set if you want to update dataTypes of an existing Schema with new data. Not for adding new columns") 
	);
	result.AddOption(new Option(new[] { "-n", "-nullvalues" },
	    "Array of values that should be converted to null. Separate values with a space") 
            { Argument = new Argument<IEnumerable<string>>() }
	);
	result.AddOption(new Option(new[] { "-o", "-output" },
	    "File name for output script. Leave blank if you only want the schema") 
            { Argument = new Argument<string>() }
	);
	result.AddOption(new Option(new[] { "-c", "-classname" },
	    "Optional File name for output c# class.") 
            { Argument = new Argument<string>() }
	);

        result.Handler = CommandHandler.Create(handler);
	return result;
    }


    public delegate int FromSchemaHandler(string input, string table,
         string schema, string output);
    public static Command FromSchemaCommand(FromSchemaHandler handler) {
        // Code
    }
}
}
3
liquidcloud9OP•

It does! Thank you for pointing me in the right direction.

1
darinclark•

you are welcome. I have updated my response with my usage pattern. Hopefully it helps.

1
Slypenslyde•

MS never made an idiomatic one for C#, and I'm not really sure if I ever found a package that seems to have widespread community support. Which is weird, it's not like console apps aren't written.

3
ClaytonDouglas•

PowerShell's Get-Help is great but I don't think you'll find anything like it for console apps. There's a few decent console app frameworks available which allow you to define your parameter sets and they autogenerate the help/usage information.

I used to produce a lot of small command line tools but now I do almost everything in PowerShell because the cmdlets/functions are so much easier to use by others, or by my future self when I've completely forgotten how the tool works.

2
liquidcloud9OP•

PowerShell because the cmdlets/functions are so much easier to use by others

Agreed. Plus, 6+ has seen such a performance boost, there’s little reason not to for most utilities. I’ve got some projects coming down the pipeline where C# may be a better fit, so this is all just practice.

2
tarluna•

Good question. I’ve never seen anything on this as well

1