简体   繁体   中英

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.

Example: 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"

An alternative to accept a list of values for a single argument is to accept the same argument multiple times. For example,

prog --file="c:\\a\\b\\c.txt" --file="c:\\prog files\\d.txt"

In which case, your code would look something like this.

List<string> fileList = new List<string>();

OptionSet options = new OptionSet
{
    { "f|file", "File name. Repeat argument for each file.", v =>
        {
            fileList.Add(v);
        }
    }
};

options.Parse(args);

IMHO, this code is easier to read and maintain.

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]);
                        break;
                    case "f":
                        Files.Add(Path.Combine(Environment.CurrentDirectory, v));
                        break;
                }
            }}
        };
options.Parse(args);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM