简体   繁体   中英

Command line parameter parsing

I'm trying to create some kind of auto login for my application via the command line. For this I've thought of the following way:

myapp.exe /autologin -u "Username" -p "Password"

Now first of all: Is this the correct approach (in terms of naming and switches?) and second: how can I make the parsing of this?

I've tried it like that, but failed (or at least I think I failed because I have to manually do string operations):

    internal static void SetStartupArguments(List<string> arguments)
    {
        IsApplicationWarmup = arguments.Contains("/warmup");
        IsApplicationAutoLogin = arguments.Contains("/autologin");

        if (IsApplicationAutoLogin)
        {
            int autoLoginIndex = arguments.FindIndex(0, str => str == "/autologin");

            if (arguments.Count >= autoLoginIndex + 1)
            {
                AutoLoginUser = arguments[autoLoginIndex + 1];
                AutoLoginPassword = string.Empty;
            }
        }
    }

The other thing is, that this is quite error prone. I can't tell if the -u or the -p switch comes first, so my fear is that I end up using the password as the username and vice-versa.

I would suggest using a 3rd party library for command-line argument parsing - it can make your life much simpler.

For example, in Noda Time we use "Command Line Parser Library" , which we actually embed into the source rather than adding it as an assembly reference. It's very simple to use - you just provide a class with attributes to say which command line option corresponds to which property. You could look at the options for our TZDB compiler as an example.

Your needs may vary of course, but it's likely that there's a library which will satisfy them - and if there isn't, that suggests that perhaps your requirements are actually too complicated for a useful command line, and you may want some other way of configuring your application, eg via a file which is itself specified on the command line.

I'd use something like https://github.com/fschwiet/ManyConsole its an extension of NDesk.Options and really easy to use for parsing command lines.

Example:

   string data = null;
   bool help   = false;
   int verbose = 0;
   var p = new OptionSet () {
    { "file=",      v => data = v },
    { "v|verbose",  v => { ++verbose } },
    { "h|?|help",   v => help = v != null },
   };
   List<string> extra = p.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