Edit

Share via


How to configure the parser in System.CommandLine

Important

System.CommandLine is currently in preview. This documentation is for version 2.0 beta 5. Some information relates to prerelease product that might be substantially modified before it's released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

ParserConfiguration is a class that provides properties to configure the parser. It is an optional argument for every Parse method, such as Command.Parse and CommandLineParser.Parse. When it isn't provided, the default configuration is used.

ParseResult has a Configuration property that returns the configuration used for parsing.

Standard output and error

InvocationConfiguration makes testing, as well as many extensibility scenarios, easier than using System.Console. It exposes two TextWriter properties: Output and Error. You can set these properties to any TextWriter instance, such as a StringWriter, which you can use to capture output for testing.

Define a simple command that writes to standard output:

Option<FileInfo?> fileOption = new("--file")
{
    Description = "An option whose argument is parsed as a FileInfo"
};

RootCommand rootCommand = new("Configuration sample")
{
    fileOption
};

rootCommand.SetAction((parseResult) =>
{
    FileInfo? fileOptionValue = parseResult.GetValue(fileOption);
    parseResult.InvocationConfiguration.Output.WriteLine(
        $"File option value: {fileOptionValue?.FullName}"
        );
});

Now, use InvocationConfiguration to capture the output:

StringWriter output = new();
rootCommand.Parse("-h").Invoke(new() { Output = output });
Debug.Assert(output.ToString().Contains("Configuration sample"));

EnablePosixBundling

Bundling of single-character options is enabled by default, but you can disable it by setting the ParserConfiguration.EnablePosixBundling property to false.

ProcessTerminationTimeout

Process termination timeout can be configured via the ProcessTerminationTimeout property. The default value is 2 seconds.

ResponseFileTokenReplacer

Response files are enabled by default, but you can disable them by setting the ResponseFileTokenReplacer property to null. You can also provide a custom implementation to customize how response files are processed.

EnableDefaultExceptionHandler

By default, all unhandled exceptions thrown during the invocation of a command are caught and reported to the user. You can disable this behavior by setting the EnableDefaultExceptionHandler property to false. This is useful when you want to handle exceptions in a custom way, such as logging them or providing a different user experience.

Derived classes

InvocationConfiguration is not sealed, so you can derive from it to add custom properties or methods. This is useful when you want to provide additional configuration options specific to your application.

See also