Friday, January 6, 2012
C# and ASP.NET - Parsing Console Arguments
It seems like the easiest things are sometimes the hardest when you are out of practice. I'm sure that's a quote from somewhere, but I can tell you it's true.
So, without any fan fair here is a simple way to parse those pesky console arguments:
public class Program
{
static void Main(string[] args)
{
try
{
//parse out console args
bool allowExecution = true;
string appDescription = "Greatest Console Ever!";
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
switch (arg)
{
case "-description":
appDescription = args[i + 1]
i++;
break;
default:
allowExecution = false;
Console.WriteLine("invalid arguments");
break;
}
}
//Execute some console command
if (allowExecution)
{
console.WriteLine(appDescription);
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
So when you run your application from the command line you would say myapp.exe -description "party rocking"
And that's it folks. Happy arg parsing.
-Matt
Subscribe to:
Posts (Atom)