Command-line arguments
suggest changeCommand-line arguments are the strings a user types after the program name: mytool --verbose -o report.txt input.csv. They are the main way to tell a console program, build tool or script what to do without recompiling it.
In C# arguments come in as a string[]:
- in a program with top-level statements, through the implicit
argsvariable - in a classic program, through the
string[] argsparameter ofMain - from anywhere in the program, through
Environment.GetCommandLineArgs()
For anything beyond a couple of flags, use a parsing library. The official one is System.CommandLine, which reached a stable 2.0 release together with .NET 10.
The args array
With top-level statements (the default for dotnet new console), the compiler provides an args variable:
Console.WriteLine($"Got {args.Length} argument(s)");
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine($"args[{i}] = [{args[i]}]");
}
$ mytool hello "two words" -v --name=Bob
Got 4 argument(s)
args[0] = [hello]
args[1] = [two words]
args[2] = [-v]
args[3] = [--name=Bob]
Points to note:
- Unlike C,
args[0]is the first real argument, not the program name. argsis nevernull. With no arguments it's an empty array, so checkargs.Lengthbefore indexing.- The runtime doesn't interpret anything.
-vand--name=Bobare just strings, and it's up to you to give them meaning.
The same program in the classic style:
class Program
{
static int Main(string[] args)
{
if (args.Length == 0)
{
Console.Error.WriteLine("usage: greet <name>");
return 1;
}
Console.WriteLine($"Hello, {args[0]}!");
return 0;
}
}
$ greet Alice
Hello, Alice!
Main can be declared as void, int, Task or Task<int>, with or without the string[] args parameter. The string[] args parameter is optional: static void Main() is fine if you don't need arguments.
Exit codes
The int returned from Main (or return 2; in top-level statements) becomes the process exit code. Scripts and CI systems check it to know whether the program succeeded. The convention is 0 for success and non-zero for failure; many Unix tools use 2 for "bad command-line usage".
if (args.Length != 1)
{
Console.Error.WriteLine("usage: count-lines <file>");
return 2;
}
if (!File.Exists(args[0]))
{
Console.Error.WriteLine($"error: file not found: {args[0]}");
return 1;
}
Console.WriteLine(File.ReadLines(args[0]).Count());
return 0;
$ count-lines missing.txt; echo "exit code: $?"
error: file not found: missing.txt
exit code: 1
Write error messages to Console.Error (stderr) so they don't mix with the real output when stdout is redirected to a file or piped. From deeper in the code you can also call Environment.Exit(code), which ends the process immediately. See Console I/O for more about stdout and stderr.
Passing arguments with dotnet run
When you run a project with dotnet run, arguments before -- go to the dotnet CLI itself and arguments after -- go to your program:
dotnet run -- --verbose file.txt
dotnet run -c Release -- --verbose file.txt # -c Release is for dotnet
Single-file programs (supported since .NET 10) work the same way:
dotnet run hello.cs -- one "two three"
args: one, two three
In Visual Studio, set arguments in the project's Properties > Debug > Open debug launch profiles UI, which stores them in Properties/launchSettings.json:
{
"profiles": {
"MyTool": {
"commandName": "Project",
"commandLineArgs": "--verbose input.csv"
}
}
}
Environment.GetCommandLineArgs
Environment.GetCommandLineArgs() returns the arguments from anywhere in the program, so you don't have to pass args around. Unlike args, element [0] is the program itself:
string[] all = Environment.GetCommandLineArgs();
Console.WriteLine(string.Join(" | ", all));
Console.WriteLine(Environment.ProcessPath);
Console.WriteLine(Environment.CommandLine);
$ mytool --verbose file.txt
C:\tools\mytool\mytool.dll | --verbose | file.txt
C:\tools\mytool\mytool.exe
C:\tools\mytool\mytool.dll --verbose file.txt
Note that [0] is the path to the .dll, even when the program was started through the .exe launcher. Use Environment.ProcessPath to get the path of the executable that's actually running, or AppContext.BaseDirectory to get the directory the app was installed into. Skip the first element to get the same values as args:
string[] userArgs = Environment.GetCommandLineArgs()[1..];
Environment.CommandLine is the whole command line as a single string. You rarely need it, since you'd have to parse it yourself.
How the command line is split into arguments
Who splits the command line into strings depends on the platform.
On Linux and macOS the shell does it. Quotes, escapes, $VARIABLES and wildcards like *.txt are processed by bash or zsh before your program starts, and your program receives the final list.
On Windows the program receives one string and the .NET runtime splits it using the same rules as the C runtime:
- whitespace separates arguments
- double quotes group text with spaces into one argument; the quotes themselves are removed
\"is a literal quote- backslashes are literal, except when they come right before a
" ""is an empty argument- wildcards are not expanded
> mytool "say \"hi\"" "" a\b *.txt "C:\dir with space\\"
args[0] = [say "hi"]
args[1] = []
args[2] = [a\b]
args[3] = [*.txt]
args[4] = [C:\dir with space\]
A common trap is a directory path with a trailing backslash: "C:\dir with space\" ends in \", which is an escaped quote, so the argument doesn't end there and swallows the rest of the line. Write "C:\dir with space\\" or drop the trailing backslash.
Because Windows doesn't expand wildcards, a portable tool that accepts patterns should expand them itself:
var files = new List<string>();
foreach (string arg in args)
{
if (arg.Contains('*') || arg.Contains('?'))
{
string dir = Path.GetDirectoryName(arg) is { Length: > 0 } d ? d : ".";
files.AddRange(Directory.EnumerateFiles(dir, Path.GetFileName(arg)));
}
else
{
files.Add(arg);
}
}
When you start another program with Process, use ProcessStartInfo.ArgumentList instead of building an Arguments string. .NET then quotes each argument correctly for you. See Running OS commands.
Parsing arguments by hand
For a small tool, a loop with a switch is enough. This parser supports short and long options, --name value and --name=value, -- to end options, and positional arguments:
bool verbose = false;
bool force = false;
string output = "out.txt";
int count = 1;
var files = new List<string>();
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
// "--" ends option parsing: everything after it is a positional argument
if (arg == "--")
{
files.AddRange(args[(i + 1)..]);
break;
}
// support --name=value in addition to --name value
string? inlineValue = null;
int eq = arg.IndexOf('=');
if (arg.StartsWith("--") && eq > 0)
{
inlineValue = arg[(eq + 1)..];
arg = arg[..eq];
}
switch (arg)
{
case "-v" or "--verbose":
verbose = true;
break;
case "-f" or "--force":
force = true;
break;
case "-o" or "--output":
output = inlineValue ?? NextValue(ref i, arg);
break;
case "-n" or "--count":
string s = inlineValue ?? NextValue(ref i, arg);
if (!int.TryParse(s, out count) || count < 1)
return Fail($"invalid value for {arg}: '{s}' (expected a positive integer)");
break;
case "-h" or "--help" or "/?":
PrintUsage();
return 0;
default:
if (arg.StartsWith('-') && arg.Length > 1)
return Fail($"unknown option: {arg}");
files.Add(arg);
break;
}
}
if (files.Count == 0)
return Fail("no input files");
Console.WriteLine($"verbose={verbose} force={force} output={output} count={count}");
Console.WriteLine($"files: {string.Join(", ", files)}");
return 0;
string NextValue(ref int i, string name)
{
if (i + 1 >= args.Length)
{
Fail($"option {name} requires a value");
Environment.Exit(2);
}
return args[++i];
}
static int Fail(string message)
{
Console.Error.WriteLine($"error: {message}");
Console.Error.WriteLine("Try 'mytool --help' for more information.");
return 2;
}
static void PrintUsage()
{
Console.WriteLine("""
Usage: mytool [options] <file>...
Options:
-o, --output <path> output file (default: out.txt)
-n, --count <n> number of repetitions (default: 1)
-f, --force overwrite existing output
-v, --verbose print more details
-h, --help show this help
""");
}
$ mytool -v --output=result.txt -n 3 a.txt b.txt
verbose=True force=False output=result.txt count=3
files: a.txt, b.txt
$ mytool -- -weird.txt a.txt
verbose=False force=False output=out.txt count=1
files: -weird.txt, a.txt
$ mytool -n abc a.txt
error: invalid value for -n: 'abc' (expected a positive integer)
Try 'mytool --help' for more information.
$ mytool -o
error: option -o requires a value
Try 'mytool --help' for more information.
Even this "simple" parser is 80 lines and still lacks combined short flags (-vf), help that stays in sync with the code, and validation of mutually exclusive options. That's where a library pays off.
System.CommandLine
System.CommandLine is the parser used by the dotnet CLI itself. It handles parsing, type conversion, validation, help text, error messages, subcommands, response files and Ctrl+C cancellation.
dotnet add package System.CommandLine
The model has three kinds of symbols:
Option<T>: a named value like--output report.txtor a flag like--verboseArgument<T>: a positional value identified by its positionCommand/RootCommand: a command with its options, arguments, subcommands and an action that runs when it's invoked
using System.CommandLine;
Argument<FileInfo[]> filesArgument = new("files")
{
Description = "Files to process",
Arity = ArgumentArity.OneOrMore,
};
Option<string> outputOption = new("--output", "-o")
{
Description = "Output file",
DefaultValueFactory = _ => "out.txt",
};
Option<int> countOption = new("--count", "-n")
{
Description = "Number of repetitions",
DefaultValueFactory = _ => 1,
};
countOption.Validators.Add(result =>
{
if (result.GetValueOrDefault<int>() < 1)
result.AddError("--count must be a positive number");
});
Option<bool> verboseOption = new("--verbose", "-v")
{
Description = "Print more details",
};
Option<string> formatOption = new("--format")
{
Description = "Output format",
DefaultValueFactory = _ => "text",
};
formatOption.AcceptOnlyFromAmong("text", "json", "csv");
RootCommand rootCommand = new("Processes files and writes a report");
rootCommand.Arguments.Add(filesArgument);
rootCommand.Options.Add(outputOption);
rootCommand.Options.Add(countOption);
rootCommand.Options.Add(verboseOption);
rootCommand.Options.Add(formatOption);
rootCommand.SetAction(parseResult =>
{
FileInfo[] files = parseResult.GetValue(filesArgument)!;
string output = parseResult.GetValue(outputOption)!;
int count = parseResult.GetValue(countOption);
bool verbose = parseResult.GetValue(verboseOption);
string format = parseResult.GetValue(formatOption)!;
Console.WriteLine($"output={output} count={count} verbose={verbose} format={format}");
foreach (FileInfo f in files)
Console.WriteLine($" {f.Name} exists={f.Exists}");
return 0;
});
ParseResult parseResult = rootCommand.Parse(args);
return parseResult.Invoke();
$ mytool -v -n 3 --format json a.txt b.txt
output=out.txt count=3 verbose=True format=json
a.txt exists=False
b.txt exists=False
$ mytool -vn 2 --format=csv a.txt
output=out.txt count=2 verbose=True format=csv
a.txt exists=False
Combined short flags (-vn 2), --name=value, and --name:value all work without extra code. Values are converted to the option's type: int, bool, double, enums, DateTime, DateOnly, TimeSpan, FileInfo, DirectoryInfo, arrays and lists of these, and nullable versions are all supported out of the box.
Invoke() runs the action and returns its result as the exit code. If parsing fails, it prints the errors and help instead and returns 1.
Generated help and errors
-h, --help and -? are added automatically, and so is --version (which prints the assembly's informational version):
$ mytool --help
Description:
Processes files and writes a report
Usage:
mytool <files>... [options]
Arguments:
<files> Files to process
Options:
-o, --output <output> Output file [default: out.txt]
-n, --count <count> Number of repetitions [default: 1]
-v, --verbose Print more details
--format <csv|json|text> Output format [default: text]
-?, -h, --help Show help and usage information
--version Show version information
Invalid input prints the help to stdout and the errors after it to stderr:
$ mytool -n 0 --format xml
--count must be a positive number
Argument 'xml' not recognized. Must be one of:
'text'
'json'
'csv'
Required argument missing for command: 'mytool'.
To handle errors yourself instead, check parseResult.Errors before calling Invoke():
ParseResult parseResult = rootCommand.Parse(args);
if (parseResult.Errors.Count > 0)
{
foreach (var error in parseResult.Errors)
Console.Error.WriteLine(error.Message);
return 2;
}
return parseResult.Invoke();
You can also skip actions altogether: call Parse(args), check for errors, and read values with parseResult.GetValue(option) in ordinary code.
Subcommands, required options and async actions
Tools like git and dotnet use subcommands (git commit, dotnet build), each with its own options. Add a Command for each one to Subcommands:
using System.CommandLine;
Option<bool> verboseOption = new("--verbose", "-v")
{
Description = "Print more details",
Recursive = true, // available on all subcommands
};
// todo add <title> [--due <date>]
Argument<string> titleArgument = new("title") { Description = "Task title" };
Option<DateOnly?> dueOption = new("--due") { Description = "Due date (yyyy-mm-dd)" };
Command addCommand = new("add", "Add a task");
addCommand.Arguments.Add(titleArgument);
addCommand.Options.Add(dueOption);
addCommand.SetAction(parseResult =>
{
string title = parseResult.GetValue(titleArgument)!;
DateOnly? due = parseResult.GetValue(dueOption);
if (parseResult.GetValue(verboseOption))
Console.WriteLine("[verbose] adding task");
Console.WriteLine($"Added '{title}'" + (due is { } d ? $" due {d:yyyy-MM-dd}" : ""));
});
// todo download <url> --out <file>
Argument<Uri> urlArgument = new("url")
{
Description = "URL to download",
// Uri has no built-in parser, so provide one
CustomParser = result =>
{
string text = result.Tokens[0].Value;
if (Uri.TryCreate(text, UriKind.Absolute, out Uri? uri))
return uri;
result.AddError($"'{text}' is not a valid absolute URL");
return null;
},
};
Option<FileInfo> outOption = new("--out")
{
Description = "Destination file",
Required = true,
};
Command downloadCommand = new("download", "Download a file");
downloadCommand.Arguments.Add(urlArgument);
downloadCommand.Options.Add(outOption);
downloadCommand.SetAction(async (parseResult, cancellationToken) =>
{
Uri url = parseResult.GetValue(urlArgument)!;
FileInfo dest = parseResult.GetValue(outOption)!;
Console.WriteLine($"Downloading {url} to {dest.Name}");
await Task.Delay(100, cancellationToken); // stands in for real work
return 0;
});
RootCommand rootCommand = new("Simple task manager");
rootCommand.Options.Add(verboseOption);
rootCommand.Subcommands.Add(addCommand);
rootCommand.Subcommands.Add(downloadCommand);
return await rootCommand.Parse(args).InvokeAsync();
$ todo add "Buy milk" --due 2026-10-20 -v
[verbose] adding task
Added 'Buy milk' due 2026-10-20
$ todo download https://example.com/a.zip --out a.zip
Downloading https://example.com/a.zip to a.zip
$ todo download not-a-url --out a.zip
'not-a-url' is not a valid absolute URL
$ todo download https://example.com/a.zip
Option '--out' is required.
$ todo add "Call Bob" --due tomorrow
Cannot parse argument 'tomorrow' for option '--due' as expected type 'System.Nullable`1[System.DateOnly]'.
Things to note:
Recursive = truemakes--verbosevalid after any subcommand, not only the root.Required = truemakes an option mandatory. Arguments are required by default; setArity = ArgumentArity.ZeroOrOneand aDefaultValueFactoryto make one optional.CustomParserconverts tokens to types the library doesn't know, and reports errors throughresult.AddError.- An async action receives a
CancellationTokenthat is cancelled when the user presses Ctrl+C. Pass it to every async call so the program stops cleanly. - Running
todowith no subcommand prints "Required command was not provided" and the help, because the root command has no action of its own.
Response files
Long command lines can be stored in a response file and passed with @. Each line holds one or more arguments:
# opts.rsp
--due 2026-12-01
--verbose
$ todo add "From rsp" @opts.rsp
[verbose] adding task
Added 'From rsp' due 2026-12-01
Response files are enabled by default. Set ResponseFileTokenReplacer = null on ParserConfiguration (passed to Parse) if @ must be treated literally, for example for arguments like @username.
Command-line arguments as configuration
ASP.NET Core and Generic Host apps already read command-line arguments into IConfiguration: WebApplication.CreateBuilder(args) and Host.CreateApplicationBuilder(args) add them as the last configuration source, so they override appsettings.json and environment variables. In a plain console app add the provider yourself:
dotnet add package Microsoft.Extensions.Configuration.CommandLine
dotnet add package Microsoft.Extensions.Configuration.Binder
using Microsoft.Extensions.Configuration;
var switchMappings = new Dictionary<string, string>
{
["-p"] = "Server:Port",
["--port"] = "Server:Port",
["-e"] = "Environment",
};
IConfiguration config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Server:Host"] = "localhost",
["Server:Port"] = "5000",
})
.AddCommandLine(args, switchMappings)
.Build();
Console.WriteLine(config["Server:Host"]);
Console.WriteLine(config.GetValue<int>("Server:Port"));
Console.WriteLine(config["Environment"] ?? "(none)");
$ server --Server:Host=example.com -p 8080 -e Production
example.com
8080
Production
The provider accepts --key=value, --key value, /key value and key=value. Hierarchical keys use :, and the switch mappings let short aliases like -p map to a full key.
This provider is for overriding settings, not for building a CLI. It has no help, no validation and no positional arguments, and every key needs a value. A bare --verbose swallows the next argument as its value: --verbose --LogLevel=Warn sets verbose to --LogLevel=Warn. Write --verbose=true instead. The Environment variables article covers the other configuration sources.
Tips
- Use a library for anything non-trivial.
System.CommandLinegives users the conventions they expect (--help,--version,--name=value,--, combined flags, clear errors) for little code. - Return meaningful exit codes and write errors to stderr. Scripts depend on both.
- Follow common conventions:
-xshort and--long-namelong options, kebab-case names,-h/--help, and--to end options so file names starting with-can be passed. - Don't pass secrets as arguments. Other users on the machine can see the command line of running processes (
ps, Task Manager), and shells save it in history. Read secrets from environment variables, files or standard input instead. - Quote paths with spaces, and remember that on Windows
\"at the end of a quoted path is an escaped quote. - Don't assume wildcard expansion. Unix shells expand
*.txtbefore your program runs; on Windows you get the literal*.txt.