Example #1
0
        public static ProgramArguments Create(string[] args)
        {
            // Using a static creation function for a command line arguments class is not required, but it's a convenient
            // way to place all command-line related functionality in one place. To parse the arguments (eg. from the Main method)
            // you then only need to call this function.
            CommandLineParser parser = new CommandLineParser(typeof(ProgramArguments));
            ProgramArguments  result = null;
            bool showFullHelp        = false;

            try
            {
                // The Parse function returns null only when the ArgumentParsed event handler cancelled parsing.
                result       = (ProgramArguments)parser.Parse(args);
                showFullHelp = result.Help;
                if (result.Help)
                {
                    showFullHelp = false;
                    switch (result.Command)
                    {
                    case Command.Add:
                        Console.WriteLine("Help specific to Add command here.");
                        break;

                    case Command.Delete:
                        Console.WriteLine("Help specific to Delete command here.");
                        break;

                    case Command.Update:
                        Console.WriteLine("Help specific to Update command here.");
                        break;

                    default:
                        showFullHelp = true;
                        break;
                    }
                }
            }
            catch (CommandLineArgumentException ex)
            {
                // We use the LineWrappingTextWriter to neatly wrap console output.
                using (LineWrappingTextWriter writer = LineWrappingTextWriter.ForConsoleError())
                {
                    // Tell the user what went wrong.
                    writer.WriteLine(ex.Message);
                    writer.WriteLine();
                }
            }

            if (showFullHelp)
            {
                // If we got here, we should print usage information to the console.
                // By default, aliases and default values are not included in the usage descriptions; for this sample, I do want to include them.
                WriteUsageOptions options = new WriteUsageOptions()
                {
                    IncludeDefaultValueInDescription = true, IncludeAliasInDescription = true
                };
                // WriteUsageToConsole automatically uses a LineWrappingTextWriter to properly word-wrap the text.
                parser.WriteUsageToConsole(options);
            }
            return(result);
        }