【问题标题】:Parse command line arguments/options in C#在 C# 中解析命令行参数/选项
【发布时间】:2017-08-31 03:49:42
【问题描述】:

我有一个带有一些参数和选项的控制台应用程序,所以我想使用免费的第三方库。

为此我找到了两个库:NDesk.OptionsCommand Line Parser Library

最后我决定使用命令行解析器库,因为使用属性更清晰,所以我下载了它并添加了对它的引用。

问题是,在添加对我的 .NET Framework 3.5 项目的引用时,我得到一个警告图标。从我下载的上面的页面中,它说兼容性是 .NET Framework 3.5+,所以我理解 3.5 是兼容的,对吗?如果不是,它的哪个先前版本与 .NET Framework 3.5 兼容?

【问题讨论】:

  • 警告是什么
  • @HimBromBeere 它说:“已解决的文件有错误的图像,没有元数据,或者无法访问。无法加载文件或程序集“c:\....\CommandLine.dll”或一个其依赖项。此程序集由比当前加载的运行时更新的运行时构建,并且无法加载“。
  • 您是否尝试过通过 nuget 安装它,包管理器控制台的命令是“Install-Package CommandLineParser -Version 1.9.71”我创建了一个 3.5 项目并运行它,它似乎正在工作。跨度>
  • @Bearcat9425 Visual Studio 2008 Professional 中的包管理器在哪里?
  • 我不确定 Nuget 在 2008 年是否“完全”受支持

标签: c# parsing command-line-parser qcommandlineparser


【解决方案1】:

您还可以使用新的 Microsoft CommandLineUtils 库。 nuget 包在这里,但仅适用于 .NET Core 或 Framrwork 4.5.2。 但是您可以下载源代码(只有 7 个文件)并包含在您的项目中。对于 Framework 3.5,您只需解决 2 个编译错误:删除一个额外的方法(使用 Tasks)和删除一行(在 HandleUnexpectedArg 中)。

要使用这个库,请在此处找到第一个示例:

static void Main(string[] args)
{
    var cmd = new CommandLineApplication();
    var argAdd = cmd.Option("-a | --add <value>", "Add a new item", CommandOptionType.SingleValue);

    cmd.OnExecute(() =>
    {
        Console.WriteLine(argAdd.Value());
        return 0;
    });

    cmd.HelpOption("-? | -h | --help");
    cmd.Execute(args);            
}

【讨论】:

【解决方案2】:

我推荐 FluentArgs(参见:https://github.com/kutoga/FluentArgs)。我认为它非常易于使用:

namespace Example
{
    using System;
    using System.Threading.Tasks;
    using FluentArgs;

    public static class Program
    {
        public static Task Main(string[] args)
        {
            return FluentArgsBuilder.New()
                .DefaultConfigsWithAppDescription("An app to convert png files to jpg files.")
                .Parameter("-i", "--input")
                    .WithDescription("Input png file")
                    .WithExamples("input.png")
                    .IsRequired()
                .Parameter("-o", "--output")
                    .WithDescription("Output jpg file")
                    .WithExamples("output.jpg")
                    .IsRequired()
                .Parameter<ushort>("-q", "--quality")
                    .WithDescription("Quality of the conversion")
                    .WithValidation(n => n >= 0 && n <= 100)
                    .IsOptionalWithDefault(50)
                .Call(quality => outputFile => inputFile =>
                {
                    /* ... */
                    Console.WriteLine($"Convert {inputFile} to {outputFile} with quality {quality}...");
                    /* ... */
                    return Task.CompletedTask;
                })
                .ParseAsync(args);
        }
    }
}

github页面上还有很多其他的例子。

【讨论】:

    【解决方案3】:

    McMaster.Extensions.CommandLineUtils 是我用过的最好的 c# 命令行解析器。我特别喜欢它很好地支持子命令。

    源码在这里:https://github.com/natemcmaster/CommandLineUtils

    dotnet add package McMaster.Extensions.CommandLineUtils
    

    这是一个如何使用属性的简单示例:

    using System;
    using McMaster.Extensions.CommandLineUtils;
    
    public class Program
    {
        public static int Main(string[] args)
            => CommandLineApplication.Execute<Program>(args);
    
        [Option(Description = "The subject")]
        public string Subject { get; } = "world";
    
        [Option(ShortName = "n")]
        public int Count { get; } = 1;
    
        private void OnExecute()
        {
            for (var i = 0; i < Count; i++)
            {
                Console.WriteLine($"Hello {Subject}!");
            }
        }
    }
    

    或者您可以使用构建器:

    using System;
    using McMaster.Extensions.CommandLineUtils;
    
    var app = new CommandLineApplication();
    
    app.HelpOption();
    
    var subject = app.Option("-s|--subject <SUBJECT>", "The subject", CommandOptionType.SingleValue);
    subject.DefaultValue = "world";
    
    var repeat = app.Option<int>("-n|--count <N>", "Repeat", CommandOptionType.SingleValue);
    repeat.DefaultValue = 1;
    
    app.OnExecute(() =>
    {
        for (var i = 0; i < repeat.ParsedValue; i++)
        {
            Console.WriteLine($"Hello {subject.Value()}!");
        }
    });
    
    return app.Execute(args);
    

    Microsoft 也一直在开发命令行解析器:https://github.com/dotnet/command-line-api,但它已经预览了很久了。

    【讨论】:

      猜你喜欢
      • 2015-07-06
      • 2013-03-07
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 2010-10-26
      相关资源
      最近更新 更多