简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM