AspNyc AspNyc - 4 years ago 271
C# Question

How to view CommandLineParser parsing errors in Visual Studio 2015?

I'm trying to see the errors that occur when parsing command-line arguments using the CommandLineParser package and Visual Studio Professional 2015 (Update 3). Here is the code I'm working with:

using System;
using System.IO;

namespace SampleParser
{
class Program
{
static void Main(string[] args)
{
// Set the CommandLineParser configuration options.
var commandLineParser = new CommandLine.Parser(x =>
{
x.MutuallyExclusive = true;
x.HelpWriter = Console.Error;
x.IgnoreUnknownArguments = false;
});

// Parse the command-line arguments.
var options = new CommandLineOptions();
var optionsAreValid = commandLineParser.ParseArguments(args, options);

if (!optionsAreValid)
{
return;
}
}
}
}


I was expecting to see some helpful info about the problems that cause
optionsAreValid
to be set to false appear in the
Debug > Windows > Output
window. However, nothing's showing up... am I doing something wrong, am I looking in the wrong place, or are there other settings that need to be toggled before I'll see this info?

UPDATE #1

Here is the class that models the command line options after being (successfully) parsed:

namespace SampleParser
{
class CommandLineOptions
{
[Option(HelpText = @"When set to ""true"", running the application will not make any changes.", Required = false)]
public bool Preview { get; set; }


[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}

Answer Source

I mistakenly assumed that the HelpText property would send info to the Visual Studio Output window; however, I was wrong. Instead, it's how the CommandLineParser gets the info it needs to write info to the console window, which pops up when running a console application project (tx @NicoE ).

Here is some boilerplate code (targeting the v2.1.1-beta NuGet package) which, while still not giving me as much info as I'd like about parser errors, exposes them in a fashion that is easier for me to handle programmatically.

// Set the CommandLineParser configuration options.
var commandLineParser = new CommandLine.Parser(x =>
{
    x.HelpWriter = null;
    x.IgnoreUnknownArguments = false;
    //x.CaseSensitive = false;
});

// Parse the command-line arguments.
CommandLineOptions options;
var errors = new List<CommandLine.Error>();

var parserResults = commandLineParser.ParseArguments<CommandLineOptions>(args)
    .WithNotParsed(x => errors = x.ToList())
    .WithParsed(x => options = x)
;

if (errors.Any())
{
    errors.ForEach(x => Console.WriteLine(x.ToString()));
    Console.ReadLine();
    return;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download