The command-line arguments are values we pass to an application when starting it to configure its behavior without modifying the code.
In C#, you can receive them through the string[] args parameter of the Main method and access each argument by its position.
How C# Receives Arguments
When a console program is executed, users often provide input parameters on the command line. For example, if you have an application called MyApplication.exe, the console arguments can be passed as follows:
MyApplication.exe file.txt /mode=debug /verboseIn this example, file.txt, /mode=debug, and /verbose are the console arguments. These arguments allow the application to receive data or instructions on how it should behave during execution.
In C#, the Main method of the program’s main class can accept these arguments through a string[] args parameter:
class Program
{
static void Main(string[] args)
{
// Here `args` will contain the arguments passed from the command line
}
}Structure of the Main Method
The Main method can receive arguments in two different ways:
-
With a
string[]parameter: This is the most common form. It allows access to all arguments passed to the program.static void Main(string[] args) { // `args` is an array of strings }Copied! -
Without parameters: In this case, arguments cannot be received from the command line.
static void Main() { // Arguments are not accessible }Copied!
Accessing Arguments
The arguments passed on the command line are available in the args parameter as an array of strings. Each argument provided by the user is stored in a specific position within the array.
Basic Example
Consider an application that receives three arguments: a file, an execution mode, and a debug option.
using System;
class Program
{
static void Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("At least three arguments are required: file, mode, and option.");
return;
}
string file = args[0];
string mode = args[1];
string option = args[2];
Console.WriteLine("File: " + file);
Console.WriteLine("Mode: " + mode);
Console.WriteLine("Option: " + option);
}
}Running the Application
If we run the program as follows:
MyApplication.exe data.txt mode=debug /verboseThe output would be:
File: data.txt
Mode: mode=debug
Option: /verboseEach value can be accessed by its index in the args array.
Checking the Number of Arguments
It is essential to check if the number of arguments matches expectations to avoid index-out-of-range errors. In the previous example, the program verifies that there are at least three arguments before attempting to access them.
Parsing Console Arguments
In many cases, console arguments have a specific format, such as key-value pairs (e.g., /mode=debug) or flag values (e.g., /verbose). To handle these types of arguments, it is common to write parsing logic that converts the arguments into usable configurations.
Parsing Key-Value Arguments
Below is an example of processing a set of arguments with a key-value format:
using System;
class Program
{
static void Main(string[] args)
{
string mode = "default";
bool verbose = false;
foreach (var arg in args)
{
if (arg.StartsWith("/mode="))
{
mode = arg.Substring(6); // Removes "/mode="
}
else if (arg == "/verbose")
{
verbose = true;
}
}
Console.WriteLine("Mode: " + mode);
Console.WriteLine("Verbose: " + verbose);
}
}Execution
When running the program with the following arguments:
MyApplication.exe /mode=debug /verboseThe output would be:
Mode: debug
Verbose: TrueThis code parses the arguments, looking for those starting with /mode= and assigns their value. If it finds the /verbose argument, it changes the verbose option’s configuration.
Validating Arguments
An important part of handling console arguments is validation. It is crucial to ensure that the provided values are correct and meet the program’s requirements.
Validating a File and a Mode
Suppose the program requires the provided file to be valid, and the execution mode must be one of the predefined values: debug, release, or test. If the argument does not meet these conditions, the program should notify the user and terminate gracefully.
using System;
class Program
{
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("At least two arguments are required: file and mode.");
return;
}
string file = args[0];
string mode = args[1];
// File validation
if (!System.IO.File.Exists(file))
{
Console.WriteLine("The specified file does not exist.");
return;
}
// Mode validation
if (mode != "debug" && mode != "release" && mode != "test")
{
Console.WriteLine("The mode must be 'debug', 'release', or 'test'.");
return;
}
Console.WriteLine($"File: {file}");
Console.WriteLine($"Mode: {mode}");
}
}Execution
If the file does not exist or the mode is incorrect, the program displays an error message. This ensures that the arguments are valid before proceeding with execution.
Handling Optional Arguments
Sometimes, console arguments are not mandatory, and we want to allow the user to decide whether to include them. For example, we might want the program to receive a file, but the mode could be optional.
using System;
class Program
{
static void Main(string[] args)
{
string file = "default.txt";
string mode = "release";
if (args.Length > 0)
{
file = args[0];
}
if (args.Length > 1)
{
mode = args[1];
}
Console.WriteLine($"File: {file}");
Console.WriteLine($"Mode: {mode}");
}
}Execution
When running the program with:
MyApplication.exe data.txtThe output would be:
File: data.txt
Mode: releaseIf the arguments are not provided, the program will use the default values.