OptionSet.Parse()
returns any unprocessed arguments. However, note that this may also includes any actual (non-option) argument of your program, e.g. input files. In that case you can't just check that nothing is returned.
E.g. parsing the below args
will return ["input.txt", "--thisOptionIsNotDefined"]
.
myprogram input.txt --thisOptionIsNotDefined
To solve this particular problem, I wrote an extension method p.ParseStrict(args)
. It simply checks that no options remain unprocessed after parsing (taking --
into account).
public static class MonoOptionsExtensions
{
public static List<string> ParseStrict(this OptionSet source, IEnumerable<string> arguments)
{
var args = arguments.ToArray();
var beforeDoubleDash = args.TakeWhile(x => x != "--");
var unprocessed = source.Parse(beforeDoubleDash);
var firstUnprocessedOpt = unprocessed.Find(x => x.Length > 0 && (x[0] == '-' || x[0] == '/'));
if (firstUnprocessedOpt != null)
throw new OptionException("Unregistered option '" + firstUnprocessedOpt + "' encountered.", firstUnprocessedOpt);
return unprocessed.Concat(args.SkipWhile(x => x != "--").Skip(1)).ToList();
}
}