日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

.NET:命令行解析器介绍

發(fā)布時(shí)間:2025/5/22 asp.net 121 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .NET:命令行解析器介绍 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

背景

經(jīng)常需要開發(fā)一下小工具,之前都是自己解析命令行參數(shù),接觸過動(dòng)態(tài)語言社區(qū)以后,發(fā)現(xiàn)命令行解析有特定的模式和框架可以利用,本文介紹一個(gè) .NET 平臺(tái)的類庫。

示例

需求

拷貝文件,如:CopyFiles -s "E:\Framework\Tenoner - 副本 (2)" -p "*.csproj" -t "E:\Framework\Tenoner - 副本 (2)\Bak",可以支持:深度拷貝、拷貝符合指定模式的文件、是否覆蓋等選秀。

使用?CommandLineParser

CommandLineParser?是一個(gè)輕量級(jí)的工具,使用非常簡答,官方也有教程。

選項(xiàng)類

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 using CommandLine; 8 using CommandLine.Text; 9 10 namespace CopyFiles 11 { 12 class Options 13 { 14 [Option( 15 's', "source", Required = true, 16 HelpText = "源目錄。")] 17 public string SourcePath { get; set; } 18 19 [Option( 20 'p', "pattern", Required = true, 21 HelpText = "文件模式。")] 22 public string SearchPattern { get; set; } 23 24 [Option( 25 't', "target", Required = true, 26 HelpText = "目標(biāo)目錄。")] 27 public string TargetPath { get; set; } 28 29 [Option('a', "all", DefaultValue = true, 30 HelpText = "是否包含所有目錄?")] 31 public bool AllDirectories { get; set; } 32 33 [Option('o', "overwrite", DefaultValue = true, 34 HelpText = "是否覆蓋所有文件?")] 35 public bool Overwrite { get; set; } 36 37 [Option('v', "verbose", DefaultValue = true, 38 HelpText = "是否打印消息?")] 39 public bool Verbose { get; set; } 40 41 [HelpOption] 42 public string GetUsage() 43 { 44 return HelpText.AutoBuild(this); 45 } 46 47 public void WriteLine(string format, params object[] args) 48 { 49 if (this.Verbose) 50 { 51 Console.WriteLine(string.Format(format, args)); 52 } 53 } 54 } 55 }

工具類

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 using CommandLine; 8 using Happy.Utils; 9 10 namespace CopyFiles 11 { 12 class Program 13 { 14 static void Main(string[] args) 15 { 16 var options = new Options(); 17 if (Parser.Default.ParseArguments(args, options)) 18 { 19 FileUtil.Copy( 20 options.SourcePath, 21 options.SearchPattern, 22 options.TargetPath, 23 (sourceFile, targetFile) => 24 { 25 options.WriteLine("拷貝文件:{0} 到 {1}", sourceFile, targetFile); 26 }, 27 (exceptionInfo) => 28 { 29 options.WriteLine(exceptionInfo.Exception.Message); 30 31 exceptionInfo.ExceptionHandled = true; 32 }, 33 options.AllDirectories, 34 options.Overwrite); 35 } 36 } 37 } 38 }

運(yùn)行效果

備注

用動(dòng)態(tài)語言寫過幾個(gè)簡單的工具,沒有堅(jiān)持下來,主要原因是對(duì) API 的不熟悉,加上目前晚上要學(xué)習(xí) Java,沒法同時(shí)在三種語言中快速的切換。

?

總結(jié)

以上是生活随笔為你收集整理的.NET:命令行解析器介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。