Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

c# - WPF Command Line Arguments, a smart way?

I'm looking for a way that I can parse command line arguments into my WPF application with just a way of reading the value of the argument that the user passed.

As an example

application.exe /setTime 5

is there a way for me to have some code where I can just say:

MessageBox.Show(arg("setTime"));

Which will output 5

Working Solution

How to create smart WPF Command Line Arguments

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way I always do it is to specify the arguments as a "name"/"value" pair e.g.

myprogram.exe -arg1 value1 -arg2 value2

This means that when you parse the command line you can put the argument/value pairs in a Dictionary with the argument as the key. Then your arg("SetTime") will become:

MessageBox.Show(dictionary["SetTime"]);

(Obviously you don't want the actual dictionary to be public.)

To get the arguments in the first place you can use:

string[] args = Environment.GetCommandLineArgs();

This will return all the arguments so you will need to parse the array in steps of two (after first checking that the length is a multiple of two + 1):

The first element of the array is the name of the executing program - MSDN Page - so your loop needs to start from one:

for (int index = 1; index < args.Length; index += 2)
{
     dictionary.Add(args[index], args[index+1]);
}

This loops in steps of two as you define each argument is a pair of values: the identifier and the actual value itself, e.g.

my.exe -arg1 value1 -arg2 value2

Then you can simply see if the argument is specified by seeing if the key -arg1 is in the dictionary and then read it's value:

string value;
if (dictionary.TryGetValue(arg, out value))
{
    // Do what ever with the value
}

This means you can have the arguments in any order and omit any arguments you don't want to specify.

The only drawback with this method is if you have a flag like -debug (for example) which could be logically implemented with the presence or absence of the flag will need to be specified as -debug true (or 1 or on), but it does simplify things if you have flags that do require values (like configuration file paths, database connection strings etc.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...