Reputation: 41
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.
Upvotes: 4
Views: 4204
Reputation: 1727
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.
Upvotes: 8
Reputation: 7658
You can use: https://learn.microsoft.com/en-us/dotnet/api/system.environment.getcommandlineargs?view=netcore-3.1
To get the command line arguments.
Environment is static so you can access this from anywhere.
Environment.GetCommandLineArgs
Upvotes: 5