Parsing required and optional command line parameters

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I'm writing a program that should accept the following parameters:

XMLfile (required)
Logfile (required)
/A (append flag, optional)
/D 123 (delay value, optional, but # should follow /D immediately)
/V 123 (version number, optional, but # should follow /V immediately)

I want the user to have the capability of specifying the optional
parameters in any order (except the required ones - XMLfile and Logfile
which should be 1st and 2nd). What's a simple way of writing a parser
for this?

Thanks!
 
Can I assume that you pass your parameters as follows

/D:123
/V:123

(i.e. no spaces between the option and value) If so, try something like
this

class Program
{
static void Main(string[] args)
{
int d;
int v;
bool error = false;

foreach (string param in args)
{
switch (param.Substring(0, 3).ToLower())
{
case "/d:":
case "-d:":
d = Convert.ToInt32(param.Substring(3));
break;
case "/v:":
case "-v:":
v = Convert.ToInt32(param.Substring(3));
break;
default:
error = true;
break;
}
}
if (error)
{
Console.WriteLine("Unknown option");
return;
}

// More code
}
}
 
You will need to adapt the code to ignore the first parameters that
aren't supplied in the format "/x:123", you could deal with this by
replacing the foreach statement with a for loop, and read from the
thrid parameter

e.g.

for (int loop = 2; loop < args.length; loop++)
{
switch (args[loop].SubString(0,3).ToLower())
// etc.

Don't forget to catch any exceptions, because your user might not
supply any parameters.
 
Back
Top