您好,登錄后才能下訂單哦!
這篇文章主要介紹了C#命令行參數(shù)解析庫System.CommandLine的使用方法,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
平常在日常的開發(fā)過程中,會經(jīng)常用到命令行工具。如cmd下的各種命令。
以下為sc命令執(zhí)行后的截圖,可以看到,由于沒有輸入任何附帶參數(shù),所以程序并未執(zhí)行任何操作,只是輸出了描述和用法。
系統(tǒng)在創(chuàng)建一個新進(jìn)程時,會傳一個命令行給它,也就是命令行字符串。
程序需要對命令行字符串進(jìn)行解析,并執(zhí)行相應(yīng)操作。
如使用sc query可以查詢當(dāng)前系統(tǒng)的服務(wù):
在C#中的控制臺程序中,Main函數(shù)中傳入的args字符串?dāng)?shù)組,就是系統(tǒng)傳入進(jìn)程的命令行參數(shù)。
在構(gòu)建具有復(fù)雜命令行參數(shù)的控制臺程序時 ,手動解析參數(shù)就變得非常麻煩。這里推薦一個開源的庫,可以更加方便的解析命令行參數(shù)。
System.CommandLine是一個基于.Net Standard 2.0(支持.Net FrameWork 4.6.1.2+和.Net Core 2.0+)的命令行參數(shù)解析庫,項目地址https://github.com/dotnet/command-line-api,目前,該項目還是屬于beta狀態(tài),期待以后的正式版本。
由于不是正式版本,在Nuget中引用時,需要鉤上Include prerelease,才能找到這個包。
Token(標(biāo)記)
命令行的每個單詞都是一個標(biāo)記,如下面的"sc"、"query"和"eventlog"都是一個Token
Commands(命令)
Commands就是應(yīng)用程序根據(jù)Token執(zhí)行相應(yīng)的操作(在System.CommandLine庫中,對應(yīng) Command類)
Root Command(根命令)
根命令是代表可執(zhí)行程序本身的Commands,如 sc(在System.CommandLine庫中,對應(yīng)RootCommand類)
SubCommands(子命令)
一些命令行程序會有SubCommands,如上面的sc query中的query就是子命令(在System.CommandLine,對應(yīng)Command類)
Options(可選項)
Options就是傳遞給Commands的命名參數(shù),如 app -myoption123中的 -myoption 123就是一個Options
Argument(參數(shù))
參數(shù)就是傳遞給選項或命令的值。
說明:
常規(guī)的調(diào)用如下:
xx.exe [options] <argument> [command]
Delimiters(分隔符)
分隔符就是把Options的命令和值分開的符號
如下三種寫法都是一樣的,可以使用空格、=或 :符號
app -myoption 123
app -myoption=123
app -myoption:123
Aliases(別名)
可以為命令或選項設(shè)置較短的別名,如
-v, --verbose
--o, --option
在下面的示例中,我們會構(gòu)建一個簡單的控制臺爬蟲工具。
1、使用Visual Studio 2019創(chuàng)建一個.Net Core控制臺程序crawler-line
2、導(dǎo)入System.CommandLine包
3、創(chuàng)建一個RootCommand
var rootCommand = new RootCommand { new Argument<string>( "url","web site url"), new Option<bool>(new string[]{ "--gethtml" ,"-html"},"Get html source"), new Option<bool>(new string[]{ "--getimage" ,"-image"},"Get images"), new Option<bool>(new string[]{ "--regex-option" ,"-regex"},"Use regex"), new Option<bool>(new string[]{ "--htmlagilitypack-option", "-agpack"},"Use HtmlAgilityPack"), new Option<bool>(new string[]{ "--anglesharp-option", "-agsharp"},"Use AngleSharp"), new Option<string>(new string[]{ "--download-path" ,"-path"},"Designate download path"),13 };
說明:
可通過Option類的構(gòu)造函數(shù)重載,為Option指定默認(rèn)值。
public Option(string alias, Func<T> getDefaultValue, string? description = null);
如上面的-path Option,指定默認(rèn)值為D:\download,如下:
new Option<string>(new string[]{ "--download-path" ,"-path"},getDefaultValue:()=>"D:\\download","Designate download path"),
也可以先實(shí)例化RootCommand對象,再通過Add的方式添加Argument和Option,如下:
var rootCommand = new RootCommand(); //添加 Argument rootCommand.AddArgument(new Argument<string>("url","web site url")); //添加 Option rootCommand.AddOption(new Option<string>(new string[] {"--download-path","-path" },"download path"));
4、添加當(dāng)前命令行程序的描述信息
rootCommand.Description = ".Net Core command-line crawler.";
5、解析Argument和Option
rootCommand.Handler = CommandHandler.Create<string, bool, bool, bool, bool, bool, string>((string url, bool html, bool image, bool regex, bool agpack, bool agsharp, string path) => { });
如果覺得參數(shù)太長,可以封裝成類,再進(jìn)行調(diào)用,如下:
public class CrawlerOption { public string Url { get; set; } public bool GetHtml { get; set; } public bool GetImage { get; set; } public bool RegexOption { get; set; } public bool HtmlagilitypackOption { get; set; } public bool AnglesharpOption { get; set; } public string DownloadPath { get; set; } }
rootCommand.Handler = CommandHandler.Create<CrawlerOption>((crawlerOption) => { })
6、添加Command并為Command添加處理函數(shù)
//添加 Command var githubCommand = new Command("github", "fork me on github"); //添加 Command的處理函數(shù) githubCommand.Handler = CommandHandler.Create(() => { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("cmd", $"/c start https://github.com/zhaotianff/Crawler-Line")); }); //將Command添加 到RootCommand rootCommand.AddCommand(githubCommand);
說明:
1、RootCommand是頂級命令,RootCommand可以添加Command,Command又可以再添加SubCommand。如此可以無限循環(huán),沒有限制 。但建議還是不要添加太多級的Command,調(diào)用的時候會不太友好
2、Command和RootCommand原理一樣,如果需要為Command添加Argument、Option和Command,可以參照前面的示例
7、調(diào)用解析
return rootCommand.InvokeAsync(args).Result;
8、調(diào)用示例
#執(zhí)行g(shù)ithub command crawler-line.exe github #執(zhí)行g(shù)ithub subcommand crawler-line.exe github sub #執(zhí)行argument option crawler-line.exe http://www.baidu.com -path "D:\test"
特別提示:
前面示例中,都是為RootCommand添加的Argument和Option,如果又指定 -path(Option),又執(zhí)行g(shù)ithub(Command)肯定會失敗。因為github這個命令是RootCommand的子命令,而-path選項是為RootCommand添加的
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“C#命令行參數(shù)解析庫System.CommandLine的使用方法”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。