最近有個程序想用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;
# 參數已經都取出來了 }