Search code examples
c#command-line-interface.net-6.0visual-studio-2022

.NET 6.0 C# "new console template" - how to read CLI arguments?


Now that .NET 6.0 is out, what appears to have be a radical update to the default CLI project template is the absence of the familiar boilerplate being reduced to the following:

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

What is not clear (and I have been trying to find documentation thus far, to no avail) is how does one access the command-line arguments passed to the executable's entrypoint class?


Solution

  • You can access the command line arguments from anywhere in your code using the Environment class.

    In particular, you can use Environment.GetCommandLineArgs:

    string name = Environment.GetCommandLineArgs()[1];
    Console.WriteLine($"Hello, {name}!");
    

    Note that the first element in the array contains the path of the executable and the arguments passed to the program start with the second element, i.e. at index 1.