Getting started
editInstall the package
Add the Meziantou.Framework.CommandLine package to a project:
dotnet package add Meziantou.Framework.CommandLineThe examples of this documentation omit the using directives: they need using Meziantou.Framework;.
Read the arguments
CommandLineParser.Current holds the arguments of the current process. Parse another array, such as the arguments of a test, with Parse:
// Parse current process arguments
var currentParser = CommandLineParser.Current;
Assert.NotNull(currentParser);
// Or parse custom arguments
var parser = new CommandLineParser();
parser.Parse(["/name=John", "/verbose", "input.txt"]);
// Check if an argument exists
Assert.True(parser.HasArgument("verbose"));
// Get named argument value
Assert.Equal("John", parser.GetArgument("name"));
// Get positional argument (the index in the array of arguments)
Assert.Equal("input.txt", parser.GetArgument(2));
// Check if help was requested: detects -?, /?, -help, /help, --help
Assert.False(parser.HelpRequested);- HasArgument tells whether a named argument is present, with or without a value.
GetArgument(string)returns the value of a named argument, andGetArgument(int)the argument at a position. Both returnnullwhen the argument does not exist.- HelpRequested is
truewhen one of-?,/?,-help,/helpor--helpis present.
CommandLineParser.Current does not include the path of the executable: position 0 is the first argument, as in the args array of the entry point.
Next steps
- Parsing arguments: the argument formats and how positions are counted.
- Quoting arguments: build a command line for another program.
- Prompts: ask the user to confirm an action.