I created a small project, which uses the CommandLineParser library.
I took a small code snippet from the guide C# Quick Start:
using System;
using CommandLine;
namespace QuickStart
{
class Program
{
public class Options
{
[Option('v', "verbose", Required = false, HelpText = "Set output to verbose messages.")]
public bool Verbose { get; set; }
}
static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args)
.WithParsed<Options>(o =>
{
if (o.Verbose)
{
Console.WriteLine($"Verbose output enabled. Current Arguments: -v {o.Verbose}");
Console.WriteLine("Quick Start Example! App is in Verbose mode!");
}
else
{
Console.WriteLine($"Current Arguments: -v {o.Verbose}");
Console.WriteLine("Quick Start Example!");
}
});
}
}
}
I can start the program via command promt with
dotnet CommandLineParserTestProject.dll
The output is as expected:
Current Arguments: -v False
Quick Start Example!
When I then put:
dotnet CommandLineParserTestProject.dll -v true
The output is again as expected:
Verbose output enabled. Current Arguments: -v True
Quick Start Example! App is in Verbose mode!
Now the problem:
After these two commands from above I enter:
dotnet CommandLineParserTestProject.dll -v false
but the output then is still:
Verbose output enabled. Current Arguments: -v True
Quick Start Example! App is in Verbose mode!
Only when I enter dotnet CommandLineParserTestProject.dll false it changes, dotnet CommandLineParserTestProject.dll -v false doesn't seem to work.
Does anybody know why this happens?
Boolean command line options do not take parameters (i.e. true/false); you either include them or you don't. Therefore the true/false parameter at the end of your command line is being ignored. Verbose output is turned on when the parser sees the -v option, and it's turned off when you omit -v from the command line.
Referring back to the documentation, you should consider handling unparsed options in the recommended way:
.WithNotParsed<Options>((errs) => HandleParseError(errs));
... which would have informed you that your true/false parameters were being ignored.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With