问题
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
回答1:
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);
回答2:
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();
回答3:
Edit: No.
But there are parsers that people have built such as...
Arguably the best out there: C# Command Line Argument Parser
回答4:
This is a fairly old post, but here's something I devised and use in all of my console applications. It's just a small snippet of code that can be injected into a single file and everything will work.
http://www.ananthonline.net/blog/dotnet/parsing-command-line-arguments-with-c-linq
Edit: This is now available on Nuget, and is part of the open-source project CodeBlocks.
It was devised to be declaratively and intuitively used, like so (another usage example here):
args.Process(
// Usage here, called when no switches are found
() => Console.WriteLine("Usage is switch0:value switch:value switch2"),
// Declare switches and handlers here
// handlers can access fields from the enclosing class, so they can set up
// any state they need.
new CommandLine.Switch(
"switch0",
val => Console.WriteLine("switch 0 with value {0}", string.Join(" ", val))),
new CommandLine.Switch(
"switch1",
val => Console.WriteLine("switch 1 with value {0}", string.Join(" ", val)), "s1"),
new CommandLine.Switch(
"switch2",
val => Console.WriteLine("switch 2 with value {0}", string.Join(" ", val))));
回答5:
If you don't like to use a library and something simple is good enough you could do this:
string[] args = Environment.GetCommandLineArgs().Skip(1).ToArray();
Func<string, string> lookupFunc =
option => args.Where(s => s.StartsWith(option)).Select(s => s.Substring(option.Length)).FirstOrDefault();
string myOption = lookupFunc("myOption=");
;
来源:https://stackoverflow.com/questions/3318829/parsing-command-line-options-in-c-sharp