Console application switches for argument values?

G

Guest

Can you create your own switches or attributes for a console app to specify
specific arguments?

In other words, specify a /f to represent the "from date" and /t as "to
date"? if I need to supply both?

Thanks, Dave
 
P

Peter Duniho

Dave said:
Can you create your own switches or attributes for a console app to
specify
specific arguments?

Yes and no. You can get at the command line arguments by using the
"Main(string[] args)" version of the program Main method. However, beyond
that you're on your own. You'll need to parse the strings yourself to turn
them into something that's usable to control your program.

I think I read something in this newsgroup recently (or possibly
microsoft.public.dotnet.framework) about a third-party class that helps map
command line arguments to some class properties or something, but I don't
recall the specific. You can use Google Groups to get more details.

Pete
 
O

Otis Mukinfus

Can you create your own switches or attributes for a console app to specify
specific arguments?

In other words, specify a /f to represent the "from date" and /t as "to
date"? if I need to supply both?

Thanks, Dave

Yes.

Here is the code...

You will need to
1. go to menu Project/YourProjectName Properties
2. On the DEBUG tab in the text box labeled "Command line arguments:" enter
/f 12/1/2006 /t 12/1/2007 (no quotes)
3. run the app

using System;
using System.Collections.Generic;

namespace TestConsole
{
class Program
{
static int Main(string[] args)
{
DateTime start = DateTime.Now; ;
DateTime end = DateTime.Now;

// for this command line:
// /f 12/1/2006 /t 12/1/2007
if (args[0] == @"/f" && args[2] == @"/t")
{

bool good = true;
if(! DateTime.TryParse(args[1], out start)){
Console.WriteLine("Invalid from date.");
good = false;
}

if (!DateTime.TryParse(args[3], out end))
{
Console.WriteLine("Invalid to date.");
good = false;
}
if (!good)
return 1;
}
else if (args[0] == @"/t" && args[2] == @"/f")
{
bool good = true;
if (!DateTime.TryParse(args[3], out start))
{
Console.WriteLine("Invalid from date.");
good = false;
}

if (!DateTime.TryParse(args[1], out end))
{
Console.WriteLine("Invalid to date.");
good = false;
}
if (!good)
return 1;
}
else
{
Console.WriteLine("Command line switches are not valid.");
}

Console.WriteLine("From = {0}, To = {1}", start, end);
Console.ReadLine();
return 0;
}
}
}

Good luck with your project,

Otis Mukinfus
http://www.arltex.com
http://www.tomchilders.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top