在C#中解析命令行参数的最佳方法?

时间:2009-01-29 13:33:28

标签: c# .net command-line-arguments

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

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

所以我对以下内容感兴趣:

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

假设命令始终遵循answered here等常用标准。

20 个答案:

答案 0 :(得分:324)

我强烈建议您使用NDesk.OptionsDocumentation)和/或Mono.Options(相同的API,不同的命名空间)。 example from the documentation

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;
}

答案 1 :(得分:198)

我非常喜欢命令行解析器库(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();
    }
}

答案 2 :(得分:50)

WPF TestApi library附带了一个用于C#开发的最好的命令行解析器。我强烈建议您从Ivo Manolov's blog on the 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);

答案 3 :(得分:24)

答案 4 :(得分:14)

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

http://bizark.codeplex.com/

此库包含command-line parser,它将使用命令行中的值初始化类。它有很多功能(我已经建立了很多年)。

来自documentation ...

BizArk框架中的命令行解析具有以下主要功能:

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

答案 5 :(得分:13)

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

答案 6 :(得分:9)

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

答案 7 :(得分:5)

这个问题有很多解决方案。为了完整性并提供备选,如果有人想要我在google code library中为两个有用的类添加这个答案。

第一个是ArgumentList,它只负责解析命令行参数。它收集由开关'/ x:y'或'-x = y'定义的名称 - 值对,并且还收集'未命名'条目的列表。这是基本的usage is discussed hereview the class here

第二部分是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:“string value”

它就像你需要的那样简单或复杂。您可以review the source codeview the helpdownload the binary

答案 8 :(得分:4)

我喜欢that one,因为您可以为参数“定义规则”,是否需要,......

或者如果你是一个Unix人,可能比你想要GNU Getopt .NET端口。

答案 9 :(得分:4)

您可能会喜欢我的Rug.Cmd

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

内置&#39; /?&#39;帮助模式。

内置&#39; / ??&#39;和&#39; /?D&#39;文件生成器模式。

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);
        }
    }
}

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

答案 10 :(得分:3)

http://www.codeplex.com/commonlibrarynet

处有一个命令行参数解析器

它可以使用
解析参数 属性
2.明确的呼叫
3.单行多个参数或字符串数​​组

它可以处理以下内容:

- 配置:Qa - startdate :$ {今天} - 区域:'纽约'设置01

它非常易于使用。

答案 11 :(得分:2)

C# CLI是我编写的一个非常简单的命令行参数解析库。它有充分的文档和开源。

答案 12 :(得分:2)

Powershell Commandlets。

PowerShell根据命令行开关上指定的属性进行解析,支持验证,参数集,流水线操作,错误报告,帮助以及最好的返回.NET对象,以便在其他命令行开关中使用。

我发现一些有用的链接:

答案 13 :(得分:2)

我最近遇到了FubuCore Command line解析实现我非常喜欢它,原因是:

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

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

首先,我为'add'命令编写了一个Command类:

[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
  ------------------------

'add'命令的示例用法:

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
  -------------------------------------

答案 14 :(得分: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;
}

答案 15 :(得分:2)

这是我根据Novell Options类编写的处理程序。

这个目标是执行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;
    }
}

答案 16 :(得分:1)

Genghis Command Line Parser可能有点过时,但它功能齐全,对我来说效果很好。

答案 17 :(得分:0)

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

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

以及概念和介绍的原始API

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

答案 18 :(得分:0)

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

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"));
    }
}

答案 19 :(得分:0)

相关问题