Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing command-line options in C# [duplicate]

I've seen people write custom classes to more easily handle command line options in various languages. I wondered if .NET (3.5 or lower) has anything built in so that you don't have to custom-parse things like:

myapp.exe file=text.txt

like image 779
Mr. Boy Avatar asked Sep 06 '25 11:09

Mr. Boy


2 Answers

For quick-and-dirty utilities where you don't need anything sophisticated, many times a console application takes command lines of the form:

program.exe command -option1 optionparameter option2 optionparameter

etc.

When that's the case, to get the 'command', just use args[0]

To get an option, use something like this:

var outputFile = GetArgument(args, "-o");

Where GetArgument is defined as:

string GetArgument(IEnumerable<string> args, string option)
    => args.SkipWhile(i => i != option).Skip(1).Take(1).FirstOrDefault();
like image 180
zumalifeguard Avatar answered Sep 09 '25 02:09

zumalifeguard


Here is another possible approach. Very simple but it has worked for me in the past.

string[] args = {"/a:b", "/c:", "/d"};
Dictionary<string, string> retval = args.ToDictionary(
     k => k.Split(new char[] { ':' }, 2)[0].ToLower(),
     v => v.Split(new char[] { ':' }, 2).Count() > 1 
                                        ? v.Split(new char[] { ':' }, 2)[1] 
                                        : null);
like image 44
Amir Aliabadi Avatar answered Sep 09 '25 02:09

Amir Aliabadi