tags:

views:

77

answers:

2

Basically, I know that some apps when called in command line with "/?" spit back a formatted list of how to call the app with params from the command line. Also, these apps sometimes even popup a box alerting the user that the program can only be run with certain params passed in and give this detailed formatted params (similar to the command prompt output).

How do they do this (The /? is more important for me than the popup box)?

+6  A: 

The Main method takes string[] parameter with the command line args.
You can also call the Environment.GetCommandLineArgs method.

You can then check whether the array contains "/?".

SLaks
This. After the executable name on the command line, anything following it separated by a space gets an element in this args array.
KeithS
@KeithS: presumably you wanted to include a hyperlink but these are removed in comments on SO.
Emile
@SLaks: But how do I actually return results to the command line after verifying "/?" was passed in. I am trying to figure out how to format my output similar to if you do "ipconfig /?" in command prompt.
myermian
To output to the command line you write to stdout (in .NET you can call println on System.out to do so)
Yuliy
@myermian: Use `Console.WriteLine` to output the help text, as already illustrated in several code examples. I'm not sure what you mean by "how do I format my output?", just create your help text and output it.
Christian Hayter
+2  A: 

Try looking at NDesk.Options. It's a single source file embeddable C# library that provides argument parsing. You can parse your arguments quickly:

public static void Main(string[] args)
{
   string data = null;
   bool help   = false;
   int verbose = 0;

   var p = new OptionSet () {
      { "file=",     "The {FILE} to work on",             v => data = v },
      { "v|verbose", "Prints out extra status messages",  v => { ++verbose } },
      { "h|?|help",  "Show this message and exit",        v => help = v != null },
   };
   List<string> extra = p.Parse(args);
}

It can write out the help screen in a professional looking format easily as well:

if (help)
{
   Console.WriteLine("Usage: {0} [OPTIONS]", EXECUTABLE_NAME);
   Console.WriteLine("This is a sample program.");
   Console.WriteLine();
   Console.WriteLine("Options:");
   p.WriteOptionDescriptions(Console.Out);
}

This gives output like so:

C:\>program.exe /?
Usage: program [OPTIONS]
This is a sample program.

Options:
  -file, --file=FILE         The FILE to work on
  -v, -verbose               Prints out extra status messages
  -h, -?, --help             Show this message and exit
sallen