.NET环境中的命令行解析类库CommandLine

最近有个程序想用C#取出命令行中的参数,记得以前用C语言编程的时候有个GetOpts挺好用的,首先从网上搜GetOpts的.NET类库,找了半天,发现都很古老了,而且没有这个类库的使用说明。

后来又找到一个CommandLineArgumentParser类库,http://commandlinearguments.codeplex.com/,但文档不多。

后来又发现 The Apache Commons CLI 类库,它可以处理各种命令行参数,可惜是个JAVA类库。

下面2个地方有相关介绍:

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

http://www.cnblogs.com/dainiao01/archive/2009/02/07/2250211.html

 

最后找到了最合适的.NET的类库CommnadLine,http://commandline.codeplex.com/,相当好用。

 

使用方法:

1)下载CommandLine.dll

2)在程序中加上引用

3)先加上using

using CommandLine;

using CommandLine.Text;

4)做个Options类

class Options

{

        // 短参数名称,长参数名称,是否是可选参数,默认值,帮助文本等

        // 第一个参数-d

        [Option("d", "dir", Required = true, HelpText = "PGN Directory to read.")]

        public string PgnDir { get; set; }

        // 第二个参数-s

        [Option("s", "step", DefaultValue = 30, HelpText = "The maximum steps in PGN game to process.")]

        public int MaxStep { get; set; }

       

        [HelpOption]

        public string GetUsage()

        {

            // 应该可以根据前面的参数设置自动生成使用说明的,这里没有使用

            var usage = new StringBuilder();

            usage.AppendLine("OpeningBook 1.0");

            usage.AppendLine("-d PgnDir [-s MaxSteps=30]");

            return usage.ToString();

        }

}

   

5)主程序Main里使用

var options = new Options();

ICommandLineParser parser = new CommandLineParser();

if (parser.ParseArguments(args, options))

{

     string pgnDir = options.PgnDir;

     int maxStep = options.MaxStep;

     // 参数取出来了,可以随便使用了

     // 本例中参数比较简单,稍微有点大材小用了

}

else  {

      Console.WriteLine(options.GetUsage());

}

 

 

最近的commandline的版本有些变化,我又用1.9.71.2版本里德了试验,当前的写法是这样:

    public class Options
    {
        // 短参数名称,长参数名称,是否是可选参数,默认值,帮助文本等
        // 第一个参数-f
        [Option('f', "file", Required = true, HelpText = "Segy Filename.")]
        public string SegyFile { get; set; }

        // 第二个参数-s
        [Option('s', "samples", DefaultValue = 15, HelpText = "keep these samples.")]
        public int NewSamples { get; set; }

        // 第三个参数-r
        [Option('r', "traces", DefaultValue = 1000, HelpText = "keep these traces.")]
        public int NewTraces { get; set; }

        [ParserState]
        public IParserState LastParserState { get; set; }

        [HelpOption]
        public string GetUsage()
        {
            return HelpText.AutoBuild(this,
              (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
        }
    }

    # 主程序的调用方法如下:
var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { string segyfile = options.SegyFile; int newSamples = options.NewSamples; int newTraces = options.NewTraces;
# 参数已经都取出来了
}

 

 

posted @ 2012-08-07 08:50  申龙斌的程序人生  阅读(4021)  评论(9编辑  收藏  举报