背景

经常需要开发一下小工具,之前都是自己解析命令行参数,接触过动态语言社区以后,发现命令行解析有特定的模式和框架可以利用,本文介绍一个 .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);
}
}
}
}

运行效果

备注

用动态语言写过几个简单的工具,没有坚持下来,主要原因是对 API 的不熟悉,加上目前晚上要学习 Java,没法同时在三种语言中快速的切换。

最新文章

  1. 从github上获取资源速度慢的解决办法
  2. JSP+Servlet+JavaBean统计页面在线访问次数
  3. mysqlbinlog 查看日志时发生报错
  4. USACO2016Splitting the Field分割牧场
  5. javascript 之正则匹配HTML
  6. iOS开发之APP推送设置WIFI
  7. Objective-C:@property参数详解
  8. VMware与Cisco etherchannel
  9. 一、换系统wince ---到 linux ubuntu 桌面
  10. [itint5]环形最大连续子段和
  11. 将Editplus添加到右键打开菜单
  12. 如何线上部署node.js项目
  13. 用Canvas写一个简单的游戏--别踩白块儿
  14. python--继承--方法的重写---和父类的扩展
  15. boost asio 学习(八) 网络基础 二进制写发送和接收
  16. jQuery 自定义函数写法分享
  17. 安装 Keepalived
  18. &与&问题
  19. Jmeter --- 组件执行顺序与作用域
  20. GDAL 地图切片层级计算公式

热门文章

  1. plt-3D打印1
  2. mysql数据库和oracle数据库之间互相导入备份
  3. CentOS7中开机出现end_request:I/O error,dev fd0,sector 0的解决办法
  4. Python 中for...esle和while...else语法
  5. [实战]MVC5+EF6+MySql企业网盘实战(14)——思考
  6. asp.net form 验证方式的使用(转载)
  7. Eclipse酷炫项目、最新趋势介绍
  8. zTree通过指定ID找到节点并选中
  9. Opencv学习笔记2:图像模糊作用和方法
  10. [APIO / CTSC2007]数据备份 --- 贪心