简体   繁体   中英

.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?

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, ie at index 1.

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 the 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 .

In Progam.cs you can just get the parameters from the args[] array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM