[2.0] Best Way to Handle Command-Line Arguments
Hi all,
Suppose I want my executable to accept the following argument format:
Code:
exename -arg1 val1 -arg2 val2
where the arguments may be in any order; some required, some optional.
Currently I am using the args parameter of the Main method, joining it into a string, and using regular expressions to get the -k v pairs. This is rather ugly.
I'd like to know if there is a neater way of handling this.
Cheers
- P
Re: [2.0] Best Way to Handle Command-Line Arguments
Let's assume that your app has three valid command line arguments: -a and -b that also require a value and -c that doesn't. I'd be inclined to do something like this:
Code:
private void Form1_Load(object sender, EventArgs e)
{
string[] args = Environment.GetCommandLineArgs();
int index = 0;
do
{
switch (args[index])
{
case "-a":
index++;
// Call a method to process the arg at index.
break;
case "-b":
index++;
// Call a method to process the arg at index.
break;
case "-c":
// Do whatever is appropriate.
break;
default:
break;
}
index++;
} while (index < args.Length);
}
If you wanted to ensure that each argument was not processed more than once then you could add a bit of validation:
Code:
private void Form1_Load(object sender, EventArgs e)
{
string[] args = Environment.GetCommandLineArgs();
List<string> processed = new List<string>();
int index = 0;
do
{
switch (args[index])
{
case "-a":
index++;
if (index < args.Length && !processed.Contains("-a"))
{
// Call a method to process the arg at index.
processed.Add("-a");
}
break;
case "-b":
index++;
if (index < args.Length && !processed.Contains("-b"))
{
// Call a method to process the arg at index.
processed.Add("-b");
}
break;
case "-c":
if (!processed.Contains("-c"))
{
// Do whatever is appropriate.
processed.Add("-c");
}
break;
default:
break;
}
index++;
} while (index < args.Length);
}
The code may be a bit lengthy but it is clear. Note that that will also just ignore invalid arguments. You might choose to notify the user of the error instead.
Re: [2.0] Best Way to Handle Command-Line Arguments
Cheers, that looks a lot neater.
Here's (roughly) what I used:
Code:
while (index < args.Length - 1)
{
switch (args[index++])
{
case "-a":
if (a == null)
a = args[index++];
break;
// etc.
default:
break;
}
}