In this example, we're using a
foreach loop to iterate over the
args array and print out each argument to the console.
Working with Command-line Arguments
Once we have access to the command-line arguments, we can use them in our program as needed. For example, we could use the arguments to specify a file to read, a database connection string, or any other configuration data needed by our program.
Here's an example of how to use command-line arguments to read a file:
static void Main(string args)
// Check if the user passed in a filename
if (args.Length > 0)
// Read the file contents
string fileContents = File.ReadAllText(args);
// Print out the file contents
Console.WriteLine("Please provide a filename as a command-line argument.");
In this example, we're checking if the user passed in a filename as a command-line argument. If they did, we're reading the file contents and printing them to the console. If they didn't pass in a filename, we're printing a message asking them to provide one.
In conclusion, passing and accessing command-line arguments in C# is a simple process. We just need to specify the arguments after the name of the program when we run it from the command-line interface, and then access them using the
args parameter in the
Main method. Once we have access to the command-line arguments, we can use them in our program as needed.