Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there .net magic to get parameter values by name in console application?

I've been developing .net console applications using C# and have always just dictated what order parameters must be inserted in so that args[0] is always start date and args[1] is always end date, for example.

however I would like to move over to using named parameters so that any combination of parameters can be sent in any order, such as the typical "-sd" would prefix a start date.

I know I could parse through the args[] looking for "-" and then read the name and look the next position for the accompanying value, but before doing that wanted to see if there was any kind of baked in handling for this rather standard practice.

is there something like this out there already that could do as such:

DateTime startDate = (DateTime)((ConsoleParameters)args[])["sd"]

I'm using C# and .Net 4

like image 804
kscott Avatar asked Sep 22 '10 20:09

kscott


2 Answers

There is nothing built into the core framework.

A lot of people think NDesk.Options is useful for this sort of thing. Check out this example (taken directly from the provided link):

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);
like image 197
Larsenal Avatar answered Nov 18 '22 06:11

Larsenal


Yes, the "magic" is that this is a common problem and it has been adequately solved. So I recommend using an already written library to handle parsing command line arguments.

CommandLineParser has been great for me. It is reasonably documented and flexible enough for every type of command line argument I've wanted to handle. Plus, it assists with usage documentation.

I will say that I'm not the biggest fan of making a specific class that has to be adorned with attributes to use this library, but it's a minor point considering that it solves my problem. And in reality forcing that attributed class pushes me to keep that class separate from where my app actually retrieves it's settings from and that always seems to be a better design.

like image 3
quentin-starin Avatar answered Nov 18 '22 07:11

quentin-starin