Search code examples
c#.netconsole-application

.NET System.CommandLine: invoking command via Parser doesn't write to console, whereas command.Invoke does


I have a console application that uses System.CommandLine to parse arguments and options.

To be able to deal with exceptions better, I've switched from RootCommand.Invoke(args) to using a CommandLineBuilder like this:

    CommandLineBuilder oCLB = new(oRootCmd);
    oCLB.UseExceptionHandler((e, c) => LogExceptionAndRaiseEvent(e));
    Parser oPrs = oCLB.Build();
    int iRC = oPrs.Invoke(p_StartupArgs);

Now I've noticed that this way of invoking doesn't write to the console anymore, neither when there is a parsing error nor when being called with the default help switch "-h".

I suspect it has to do with the second parameter in Invoke, which is can be an IConsole (and is NULL by default), but I don't have a real clue and wouldn't know what to pass there.

UPDATE: see solution below, using some CommandLineBuilder configuration options.


Solution

  • Update, the solution was adding some more "Use" configuration to the CommandLineBuilder:

          CommandLineBuilder oCLB = new(oRootCmd);
          oCLB.UseHelp().
            UseVersionOption().
            UseParseErrorReporting();
          oCLB.UseExceptionHandler((e, c) => BygLog.LogExceptionAndRaiseEvent(e));
          Parser oPrs = oCLB.Build();
          int iRC = oPrs.Invoke(p_StartupArgs, new SystemConsole());
    

    As per https://github.com/dotnet/command-line-api/issues/2188