.net core 获取.NET核心工作程序服务CommandLineConfigurationProvider参数

.net core 获取.NET核心工作程序服务CommandLineConfigurationProvider参数,.net-core,.net Core,我正在创建一个.NET Core Worker服务应用程序,需要将命令行参数传递到该应用程序中。我可以通过IConfiguration configuration>Providers>CommandLineConfigurationProvider在调试时看到参数,但不知道如何编写代码以获取参数 感谢您的帮助。您可以使用: 获取命令行参数 环境是静态的,所以您可以从任何地方访问它 Environment.GetCommandLineArgs 如果有提供IConfiguration的对象配置,

我正在创建一个.NET Core Worker服务应用程序,需要将命令行参数传递到该应用程序中。我可以通过IConfiguration configuration>Providers>CommandLineConfigurationProvider在调试时看到参数,但不知道如何编写代码以获取参数

感谢您的帮助。

您可以使用:

获取命令行参数

环境是静态的,所以您可以从任何地方访问它

Environment.GetCommandLineArgs 
如果有提供IConfiguration的对象配置,只需使用config.GetValuemyvaluename

例如:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return new HostBuilder()
        .ConfigureAppConfiguration((context, cfg) =>
        {
            cfg.AddCommandLine(args);
        });
}
要获取配置,请执行以下操作:

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
}

CommandLineConfigurationProvider非常基本,因此它不支持二进制选项present/not present等复杂模式。

这似乎可行。在调试模式下使用此选项时,必须跳过第一个元素,因为它似乎在DLL路径中传递。我在想还有别的办法。我现在正在使用你的建议。谢谢你。@Shaggy很好。你的问题现在满意了吗?如果是,请将答案标记为已完成-如果不是,您缺少什么?
myprogram.exe --myvalue abcd