731

在构建带参数的控制台应用程序时,您可以使用传递给Main(string[] args).

在过去,我只是简单地索引/循环该数组并执行了一些正则表达式来提取值。但是,当命令变得更复杂时,解析会变得非常难看。

所以我感兴趣:

  • 您使用的库
  • 您使用的模式

假设命令始终遵守通用标准,例如在此处回答

4

20 回答 20

324

我强烈建议使用NDesk.Options文档)和/或Mono.Options(相同的 API,不同的命名空间)。文档中的一个示例

bool show_help = false;
List<string> names = new List<string> ();
int repeat = 1;

var p = new OptionSet () {
    { "n|name=", "the {NAME} of someone to greet.",
       v => names.Add (v) },
    { "r|repeat=", 
       "the number of {TIMES} to repeat the greeting.\n" + 
          "this must be an integer.",
        (int v) => repeat = v },
    { "v", "increase debug message verbosity",
       v => { if (v != null) ++verbosity; } },
    { "h|help",  "show this message and exit", 
       v => show_help = v != null },
};

List<string> extra;
try {
    extra = p.Parse (args);
}
catch (OptionException e) {
    Console.Write ("greet: ");
    Console.WriteLine (e.Message);
    Console.WriteLine ("Try `greet --help' for more information.");
    return;
}
于 2010-01-14T22:06:25.820 回答
197

我真的很喜欢命令行解析器库(http://commandline.codeplex.com/)。它有一种非常简单优雅的通过属性设置参数的方式:

class Options
{
    [Option("i", "input", Required = true, HelpText = "Input file to read.")]
    public string InputFile { get; set; }

    [Option(null, "length", HelpText = "The maximum number of bytes to process.")]
    public int MaximumLenght { get; set; }

    [Option("v", null, HelpText = "Print details during execution.")]
    public bool Verbose { get; set; }

    [HelpOption(HelpText = "Display this help screen.")]
    public string GetUsage()
    {
        var usage = new StringBuilder();
        usage.AppendLine("Quickstart Application 1.0");
        usage.AppendLine("Read user manual for usage instructions...");
        return usage.ToString();
    }
}
于 2011-09-07T07:29:53.247 回答
50

WPF TestApi 库带有用于 C# 开发的最佳命令行解析器之一。我强烈建议从Ivo Manolov 的 API 博客中查看它:

// EXAMPLE #2:
// Sample for parsing the following command-line:
// Test.exe /verbose /runId=10
// This sample declares a class in which the strongly-
// typed arguments are populated
public class CommandLineArguments
{
   bool? Verbose { get; set; }
   int? RunId { get; set; }
}

CommandLineArguments a = new CommandLineArguments();
CommandLineParser.ParseArguments(args, a);
于 2009-01-29T14:12:55.900 回答
24

看看http://github.com/mono/mono/tree/master/mcs/class/Mono.Options/

于 2009-01-29T13:40:58.537 回答
14

看起来每个人都有自己的宠物命令行解析器,我最好也添加我的:)。

http://bizark.codeplex.com/

这个库包含一个命令行解析器,它将使用命令行中的值初始化一个类。它有很多功能(我多年来一直在构建它)。

文档...

BizArk 框架中的命令行解析具有以下关键特性:

  • 自动初始化:根据命令行参数自动设置类属性。
  • 默认属性:在不指定属性名称的情况下发送值。
  • 值转换:使用 BizArk 中也包含的强大的 ConvertEx 类将值转换为正确的类型。
  • 布尔标志:可以通过简单地使用参数(例如,/b 表示真,/b- 表示假)或添加值 true/false、yes/no 等来指定标志。
  • 参数数组:只需在命令行名称后添加多个值即可设置定义为数组的属性。例如,/x 1 2 3 将使用数组 { 1, 2, 3 } 填充 x(假设 x 被定义为整数数组)。
  • 命令行别名:一个属性可以支持多个命令行别名。例如,帮助使用别名 ?。
  • 部分名称识别:您不需要拼出全名或别名,只需拼写足以让解析器区分属性/别名与其他名称。
  • 支持 ClickOnce:即使在 ClickOnce 部署的应用程序的 URL 中将属性指定为查询字符串,也可以初始化属性。命令行初始化方法将检测它是否作为 ClickOnce 运行,因此您的代码在使用时无需更改。
  • 自动创建 /? help:这包括考虑到控制台宽度的漂亮格式。
  • 将命令行参数加载/保存到文件:如果您有多个要运行多次的大型复杂命令行参数集,这将特别有用。
于 2010-07-01T01:03:02.100 回答
13

不久前我写了一个 C# 命令行参数解析器。它位于: http: //www.codeplex.com/CommandLineArguments

于 2009-12-15T07:07:43.817 回答
9

CLAP(命令行参数解析器)有一个可用的 API,并且有很好的文档记录。您创建一个方法,注释参数。 https://github.com/adrianaisemberg/CLAP

于 2012-03-15T15:11:25.787 回答
5

这个问题有很多解决方案。为了完整性并提供替代方案,如果有人希望我在我的谷歌代码库中为两个有用的类添加这个答案。

第一个是ArgumentList,它只负责解析命令行参数。它收集由开关“/x:y”或“-x=y”定义的名称-值对,还收集“未命名”条目的列表。它的基本用法在这里讨论,在这里查看课程

第二部分是CommandInterpreter,它从您的 .Net 类中创建一个功能齐全的命令行应用程序。举个例子:

using CSharpTest.Net.Commands;
static class Program
{
    static void Main(string[] args)
    {
        new CommandInterpreter(new Commands()).Run(args);
    }
    //example ‘Commands’ class:
    class Commands
    {
        public int SomeValue { get; set; }
        public void DoSomething(string svalue, int ivalue)
        { ... }

使用上面的示例代码,您可以运行以下命令:

Program.exe DoSomething“字符串值”5

- 或者 -

Program.exe dosomething /ivalue=5 -svalue:"字符串值"

它就像那样简单,也可以像您需要的那样复杂。您可以查看源代码查看帮助下载二进制文件

于 2010-05-11T18:25:59.837 回答
4

我喜欢那个,因为您可以为参数“定义规则”,无论是否需要,...

或者,如果您是 Unix 人,那么您可能会喜欢GNU Getopt .NET端口。

于 2009-01-29T13:43:09.610 回答
4

你可能喜欢我的一个Rug.Cmd

易于使用和可扩展的命令行参数解析器。句柄:布尔、加/减、字符串、字符串列表、CSV、枚举。

内置“/?” 帮助模式。

内置'/??' 和 '/?D' 文档生成器模式。

static void Main(string[] args) 
{            
    // create the argument parser
    ArgumentParser parser = new ArgumentParser("ArgumentExample", "Example of argument parsing");

    // create the argument for a string
    StringArgument StringArg = new StringArgument("String", "Example string argument", "This argument demonstrates string arguments");

    // add the argument to the parser 
    parser.Add("/", "String", StringArg);

    // parse arguemnts
    parser.Parse(args);

    // did the parser detect a /? argument 
    if (parser.HelpMode == false) 
    {
        // was the string argument defined 
        if (StringArg.Defined == true)
        {
            // write its value
            RC.WriteLine("String argument was defined");
            RC.WriteLine(StringArg.Value);
        }
    }
}

编辑:这是我的项目,因此不应将这个答案视为第三方的认可。也就是说,我确实将它用于我编写的每个基于命令行的程序,它是开源的,我希望其他人可以从中受益。

于 2012-01-23T16:55:08.007 回答
3

在http://www.codeplex.com/commonlibrarynet有一个命令行参数解析器


它可以使用1. 属性
2. 显式调用
3. 单行多参数或字符串数​​组来解析参数

它可以处理以下事情:

-配置:Qa -开始日期:${今天} -地区:'New York' Settings01

它非常易于使用。

于 2009-04-17T21:28:20.723 回答
2

这是我基于 NovellOptions类编写的处理程序。

这个针对执行while (input !="exit")样式循环的控制台应用程序,例如 FTP 控制台等交互式控制台。

示例用法:

static void Main(string[] args)
{
    // Setup
    CommandHandler handler = new CommandHandler();
    CommandOptions options = new CommandOptions();

    // Add some commands. Use the v syntax for passing arguments
    options.Add("show", handler.Show)
        .Add("connect", v => handler.Connect(v))
        .Add("dir", handler.Dir);

    // Read lines
    System.Console.Write(">");
    string input = System.Console.ReadLine();

    while (input != "quit" && input != "exit")
    {
        if (input == "cls" || input == "clear")
        {
            System.Console.Clear();
        }
        else
        {
            if (!string.IsNullOrEmpty(input))
            {
                if (options.Parse(input))
                {
                    System.Console.WriteLine(handler.OutputMessage);
                }
                else
                {
                    System.Console.WriteLine("I didn't understand that command");
                }

            }

        }

        System.Console.Write(">");
        input = System.Console.ReadLine();
    }
}

来源:

/// <summary>
/// A class for parsing commands inside a tool. Based on Novell Options class (http://www.ndesk.org/Options).
/// </summary>
public class CommandOptions
{
    private Dictionary<string, Action<string[]>> _actions;
    private Dictionary<string, Action> _actionsNoParams;

    /// <summary>
    /// Initializes a new instance of the <see cref="CommandOptions"/> class.
    /// </summary>
    public CommandOptions()
    {
        _actions = new Dictionary<string, Action<string[]>>();
        _actionsNoParams = new Dictionary<string, Action>();
    }

    /// <summary>
    /// Adds a command option and an action to perform when the command is found.
    /// </summary>
    /// <param name="name">The name of the command.</param>
    /// <param name="action">An action delegate</param>
    /// <returns>The current CommandOptions instance.</returns>
    public CommandOptions Add(string name, Action action)
    {
        _actionsNoParams.Add(name, action);
        return this;
    }

    /// <summary>
    /// Adds a command option and an action (with parameter) to perform when the command is found.
    /// </summary>
    /// <param name="name">The name of the command.</param>
    /// <param name="action">An action delegate that has one parameter - string[] args.</param>
    /// <returns>The current CommandOptions instance.</returns>
    public CommandOptions Add(string name, Action<string[]> action)
    {
        _actions.Add(name, action);
        return this;
    }

    /// <summary>
    /// Parses the text command and calls any actions associated with the command.
    /// </summary>
    /// <param name="command">The text command, e.g "show databases"</param>
    public bool Parse(string command)
    {
        if (command.IndexOf(" ") == -1)
        {
            // No params
            foreach (string key in _actionsNoParams.Keys)
            {
                if (command == key)
                {
                    _actionsNoParams[key].Invoke();
                    return true;
                }
            }
        }
        else
        {
            // Params
            foreach (string key in _actions.Keys)
            {
                if (command.StartsWith(key) && command.Length > key.Length)
                {

                    string options = command.Substring(key.Length);
                    options = options.Trim();
                    string[] parts = options.Split(' ');
                    _actions[key].Invoke(parts);
                    return true;
                }
            }
        }

        return false;
    }
}
于 2009-08-21T07:27:24.743 回答
2

我个人最喜欢的是Peter Palotas 的http://www.codeproject.com/KB/recipes/plossum_commandline.aspx

[CommandLineManager(ApplicationName="Hello World",
    Copyright="Copyright (c) Peter Palotas")]
class Options
{
   [CommandLineOption(Description="Displays this help text")]
   public bool Help = false;

   [CommandLineOption(Description = "Specifies the input file", MinOccurs=1)]
   public string Name
   {
      get { return mName; }
      set
      {
         if (String.IsNullOrEmpty(value))
            throw new InvalidOptionValueException(
                "The name must not be empty", false);
         mName = value;
      }
   }

   private string mName;
}
于 2011-05-12T06:08:45.837 回答
2

我最近遇到了我非常喜欢的 FubuCore 命令行解析实现,原因是:

  • 它很容易使用——虽然我找不到它的文档,但 FubuCore 解决方案还提供了一个包含一组很好的单元测试的项目,这些单元测试比任何文档都更能说明功能
  • 它有一个很好的面向对象设计,没有代码重复或我以前在命令行解析应用程序中使用的其他类似东西
  • 它是声明性的:您基本上为命令和参数集编写类,并用属性装饰它们以设置各种选项(例如名称、描述、强制/可选)
  • 该库甚至根据这些定义打印出一个很好的使用图

下面是一个关于如何使用它的简单示例。为了说明用法,我编写了一个简单的实用程序,它有两个命令: - add(将对象添加到列表 - 对象由名称(字符串)、值(int)和布尔标志组成) - list(列表所有当前添加的对象)

首先,我为“添加”命令编写了一个命令类:

[Usage("add", "Adds an object to the list")]
[CommandDescription("Add object", Name = "add")]
public class AddCommand : FubuCommand<CommandInput>
{
    public override bool Execute(CommandInput input)
    {
        State.Objects.Add(input); // add the new object to an in-memory collection

        return true;
    }
}

此命令将 CommandInput 实例作为参数,因此我接下来定义:

public class CommandInput
{
    [RequiredUsage("add"), Description("The name of the object to add")]
    public string ObjectName { get; set; }

    [ValidUsage("add")]
    [Description("The value of the object to add")]
    public int ObjectValue { get; set; }

    [Description("Multiply the value by -1")]
    [ValidUsage("add")]
    [FlagAlias("nv")]
    public bool NegateValueFlag { get; set; }
}

下一个命令是'list',实现如下:

[Usage("list", "List the objects we have so far")]
[CommandDescription("List objects", Name = "list")]
public class ListCommand : FubuCommand<NullInput>
{
    public override bool Execute(NullInput input)
    {
        State.Objects.ForEach(Console.WriteLine);

        return false;
    }
}

'list' 命令不带参数,所以我为此定义了一个 NullInput 类:

public class NullInput { }

现在剩下的就是将其连接到 Main() 方法中,如下所示:

    static void Main(string[] args)
    {
        var factory = new CommandFactory();
        factory.RegisterCommands(typeof(Program).Assembly);

        var executor = new CommandExecutor(factory);

        executor.Execute(args);
    }

该程序按预期工作,打印有关正确用法的提示,以防任何命令无效:

  ------------------------
    Available commands:
  ------------------------
     add -> Add object
    list -> List objects
  ------------------------

以及“添加”命令的示例用法:

Usages for 'add' (Add object)
  add <objectname> [-nv]

  -------------------------------------------------
    Arguments
  -------------------------------------------------
     objectname -> The name of the object to add
    objectvalue -> The value of the object to add
  -------------------------------------------------

  -------------------------------------
    Flags
  -------------------------------------
    [-nv] -> Multiply the value by -1
  -------------------------------------
于 2011-06-11T06:50:37.453 回答
2

Powershell 命令行开关。

Powershell 基于命令行开关上指定的属性完成解析,支持验证、参数集、流水线、错误报告、帮助,以及最好的返回 .NET 对象以在其他命令行开关中使用。

我发现几个链接对入门很有帮助:

于 2012-07-07T05:07:43.860 回答
2

C# CLI是我编写的一个非常简单的命令行参数解析库。它有据可查且开源。

于 2012-08-11T15:02:34.917 回答
1

Genghis Command Line Parser 可能有点过时了,但它的功能非常完整,对我来说效果很好。

于 2009-08-21T11:07:24.190 回答
0

我建议使用开源库CSharpOptParse。它解析命令行并使用命令行输入来水合用户定义的 .NET 对象。在编写 C# 控制台应用程序时,我总是求助于这个库。

于 2010-07-23T14:09:11.607 回答
0

请使用 apache commons cli API 的 .net 端口。这很好用。

http://sourceforge.net/projects/dotnetcli/

以及用于概念和介绍的原始 API

http://commons.apache.org/cli/

于 2011-06-28T09:04:55.870 回答
0

一个非常简单易用的临时类,用于命令行解析,支持默认参数。

class CommandLineArgs
{
    public static CommandLineArgs I
    {
        get
        {
            return m_instance;
        }
    }

    public  string argAsString( string argName )
    {
        if (m_args.ContainsKey(argName)) {
            return m_args[argName];
        }
        else return "";
    }

    public long argAsLong(string argName)
    {
        if (m_args.ContainsKey(argName))
        {
            return Convert.ToInt64(m_args[argName]);
        }
        else return 0;
    }

    public double argAsDouble(string argName)
    {
        if (m_args.ContainsKey(argName))
        {
            return Convert.ToDouble(m_args[argName]);
        }
        else return 0;
    }

    public void parseArgs(string[] args, string defaultArgs )
    {
        m_args = new Dictionary<string, string>();
        parseDefaults(defaultArgs );

        foreach (string arg in args)
        {
            string[] words = arg.Split('=');
            m_args[words[0]] = words[1];
        }
    }

    private void parseDefaults(string defaultArgs )
    {
        if ( defaultArgs == "" ) return;
        string[] args = defaultArgs.Split(';');

        foreach (string arg in args)
        {
            string[] words = arg.Split('=');
            m_args[words[0]] = words[1];
        }
    }

    private Dictionary<string, string> m_args = null;
    static readonly CommandLineArgs m_instance = new CommandLineArgs();
}

class Program
{
    static void Main(string[] args)
    {
        CommandLineArgs.I.parseArgs(args, "myStringArg=defaultVal;someLong=12");
        Console.WriteLine("Arg myStringArg  : '{0}' ", CommandLineArgs.I.argAsString("myStringArg"));
        Console.WriteLine("Arg someLong     : '{0}' ", CommandLineArgs.I.argAsLong("someLong"));
    }
}
于 2011-06-29T12:43:58.510 回答