I creating a .NET Core Worker Service app and need to get the Command-Line arguments passed into the app. I can see the arguments while debugging via the IConfiguration configuration > Providers > CommandLineConfigurationProvider, but don't know how to code it to get the arguments.
Any help is appreciated.
If you have an object config that provides IConfiguration you simply use config.GetValue<string>("myvaluename").
For example:
public static IHostBuilder CreateHostBuilder(string[] args)
{
return new HostBuilder()
.ConfigureAppConfiguration((context, cfg) =>
{
cfg.AddCommandLine(args);
});
}
To get the config:
static void Main(string[] args)
{
using var host = CreateHostBuilder(args).Build();
var config = host.Services.GetRequiredService<IConfiguration>();
var myvalue = config.GetValue<string>("myvalue");
// .... myvalue may be null if not specified
}
Finally, you invoke your program like this:
myprogram.exe --myvalue abcd
The CommandLineConfigurationProvider is pretty basic, so it doesn't support complex patterns like binary options (present/not present), etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With