Shaggy
Shaggy

Reputation: 41

Get .NET Core Worker Service CommandLineConfigurationProvider Arguments

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

Answers (2)

Guillermo Prandi
Guillermo Prandi

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

sommmen
sommmen

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

Related Questions