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
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With