.NET命令行解析器示例程序(命令行选项功能)
示例需求
拷贝文件,如:copyfiles -s "e:\framework\tenoner - 副本 (2)" -p "*.csproj" -t "e:\framework\tenoner - 副本 (2)\bak",可以支持:深度拷贝、拷贝符合指定模式的文件、是否覆盖等选项。
使用 commandlineparser
commandlineparser 是一个轻量级的工具,使用非常简答,官方也有教程。
选项类
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using commandline;
using commandline.text;
namespace copyfiles
{
class options
{
[option(
's', "source", required = true,
helptext = "源目录。")]
public string sourcepath { get; set; }
[option(
'p', "pattern", required = true,
helptext = "文件模式。")]
public string searchpattern { get; set; }
[option(
't', "target", required = true,
helptext = "目标目录。")]
public string targetpath { get; set; }
[option('a', "all", defaultvalue = true,
helptext = "是否包含所有目录?")]
public bool alldirectories { get; set; }
[option('o', "overwrite", defaultvalue = true,
helptext = "是否覆盖所有文件?")]
public bool overwrite { get; set; }
[option('v', "verbose", defaultvalue = true,
helptext = "是否打印消息?")]
public bool verbose { get; set; }
[helpoption]
public string getusage()
{
return helptext.autobuild(this);
}
public void writeline(string format, params object[] args)
{
if (this.verbose)
{
console.writeline(string.format(format, args));
}
}
}
}
工具类
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using commandline;
using happy.utils;
namespace copyfiles
{
class program
{
static void main(string[] args)
{
var options = new options();
if (parser.default.parsearguments(args, options))
{
fileutil.copy(
options.sourcepath,
options.searchpattern,
options.targetpath,
(sourcefile, targetfile) =>
{
options.writeline("拷贝文件:{0} 到 {1}", sourcefile, targetfile);
},
(exceptioninfo) =>
{
options.writeline(exceptioninfo.exception.message);
exceptioninfo.exceptionhandled = true;
},
options.alldirectories,
options.overwrite);
}
}
}
}