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

Time:11-28

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?

CodePudding user response:

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.

CodePudding user response:

New project templates are using C# 9 feature called top-level statements.

For top-level statement file compiler will generate string[] args parameter (actually it generates whole class containing Main method), so you can just use it (as previously was done with Main(string[] args)):

Console.WriteLine(args.Length);

More info about genration patterns can be found in the docs.

  • Related