开发者

C#: How do I add a response to "/?" in my program

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)?


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 "/?".


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜