Parsing console application arguments [closed]

Posted on

Problem

In our console app, the parsing of application arguments is done like so:

using System.Linq;

namespace Generator
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            var param1 = args.SingleOrDefault(arg => arg.StartsWith("p1:"));
            if (!string.IsNullOrEmpty(param1))
            {
                param1  = param1.Replace("p1:", "");
            }
            //...
        }
    }
}

It’s supposed to be called like this:

`Generator.exe p1:somevalue`

Is there a better/simpler way to parse arguments?

Solution

I’d recommend taking advantage of the excellent Mono.Options module. It’s a single .cs file you can drop in to your solution and get full-featured parsing of GNU getopt-style command lines. (Things like -x -y -z, which is equivalent to -xyz, or -k value, or --long-opt, and so forth.)

With such an implementation you will have to repeat yourself for each param.

Alternative:

var parsedArgs = args
    .Select(s => s.Split(new[] {':'}, 1))
    .ToDictionary(s => s[0], s => s[1]);
string p1 = parsedArgs["p1"];

There’s a related question on Stack Overflow. There, the consensus seems to be Mono.Options as already suggested here by josh3736.

I usually don’t use complex command line arguments, so I use a very Simple Command Line Arguments Parser, but it can be used as a foundation for your own application specific parameter presenter.

You could use foreach for iterating through the agruments and then for your argument with index 1 you could use regular expression to retrieve parsed text after p1:

Leave a Reply

Your email address will not be published. Required fields are marked *