iwo iwo - 1 month ago 10
C# Question

How to parse a simple list of items with NDesk Options in C#

I am new to the NDesk.Options library. Can't figure out the simplest way to parse a simple list of items.

prog --items=item1 item2 item3
(I want to use a List items in the code)

It should support quoting as well as I want to use the item list as list of file or dir names.

prog --items="c:\a\b\c.txt" "c:\prog files\d.txt"
prog --dirs="c:\prog files\" "d:\x\y\space in dirname"


You can use the "<>" input which denotes that no flag was associated with the input. Since the options are read left-to-right, you can set a 'currentParameter' flag when the starting flag is encountered, and assume any subsequent inputs without a flag are part of the list. Here is an example where we can specify a List as the input Files, and a Dictionary (Parameters) which are a list of key-value pairs. Other variations are of course available as well.

OptionSet options = new OptionSet()
            {"f|file", "a list of files" , v => {
                currentParameter = "f";
            {"p", @"Parameter values to use for variable resolution in the xml - use the form 'Name=Value'.  a ':' or ';' may be used in place of the equals sign", v => {
                currentParameter = "p";
            { "<>", v => {
                switch(currentParameter) {
                    case "p":
                        string[] items = v.Split(new[]{'=', ':', ';'}, 2);
                        Parameters.Add(items[0], items[1]);
                    case "f":
                        Files.Add(Path.Combine(Environment.CurrentDirectory, v));