控制台程序的参数解析类库 CommandLine

时间:2021-05-01 20:55:30

C#控制台程序的参数解析类库 CommandLine简单使用说明

前言

C#开发的控制台程序,默认接收string[] args参数。如果有多个参数需要输入时,可以按照顺序依次输入;但如果有些参数不是必选的,或者有些参数中间需要有空格比如时间“2016-05-18 24:35:00”,处理起来就比较麻烦了。一些常用的命令行工具都会提供指定参数的方式,比如:curl

C:\Users\Administrator>curl --help
Usage: curl [options...] <url>
Options: (H) means HTTP/HTTPS only, (F) means FTP only
--anyauth Pick "any" authentication method (H)
-a/--append Append to target file when uploading (F)
--basic Use HTTP Basic Authentication (H)
--cacert <file> CA certificate to verify peer against (SSL)
--capath <directory> CA directory to verify peer against (SSL)
-E/--cert <cert[:passwd]> Client certificate file and password (SSL)

这里要介绍的 CommandLine就是帮助我们轻易完成参数接收和帮助输出的开源类库,同时它可以把接收到的参数转换成对象,方便程序的处理。

教程

  1. 新建控制台项目,安装CommandLine。

    可以下载、编译、引用CommandLine.dll,也可以使用nuget安装 Install-Package CommandLineParser

  2. 新建参数说明类 Options 

首先,添加命名空间  

using CommandLine;
using CommandLine.Text;

然后,定义Options 类

控制台程序的参数解析类库 CommandLine
 1   class Options
2 {
3 [Option('r', "read", MetaValue = "FILE", Required = true, HelpText = "输入数据文件")]
4 public string InputFile { get; set; }
5
6 [Option('w', "write", MetaValue = "FILE", Required = false, HelpText = "输出数据文件")]
7 public string OutputFile { get; set; }
8
9
10 [Option('s', "start-time", MetaValue = "STARTTIME", Required = true, HelpText = "开始时间")]
11 public DateTime StartTime { get; set; }
12
13 [Option('e', "end-time", MetaValue = "ENDTIME", Required = true, HelpText = "结束时间")]
14 public DateTime EndTime { get; set; }
15
16
17 [HelpOption]
18 public string GetUsage()
19 {
20 return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
21 }
22
23 }
控制台程序的参数解析类库 CommandLine

  3. 修改控制台主程序 Program的Main函数  

控制台程序的参数解析类库 CommandLine
 1   //输出信息时的头信息
2 private static readonly HeadingInfo HeadingInfo = new HeadingInfo("演示程序", "V1.8");
3
4 static void Main(string[] args)
5 {
6 //这种输出会在前面添加"演示程序"几个字
7 HeadingInfo.WriteError("包含头信息的错误数据");
8 HeadingInfo.WriteMessage("包含头信息的消息数据");
9
10 Console.WriteLine("不包含头信息的错误数据");
11 Console.WriteLine("不包含头信息的消息数据");
12
13 var options = new Options();
14 if (CommandLine.Parser.Default.ParseArguments(args, options))
15 {
16 Console.WriteLine("Input File:" + options.InputFile);
17 Console.WriteLine("Output File:" + options.OutputFile);
18
19 Console.WriteLine("开始时间:" + options.StartTime.ToString("yyyy年MM月dd日 HH点mm分"));
20 Console.WriteLine("结束时间:" + options.EndTime.ToString("yyyy年MM月dd日 HH点mm分"));
21 Console.Read();
22 }
23 //else
24 //{
25 // Console.WriteLine(options.GetUsage());
26 // Console.Read();
27 //}
28
29 Console.Read();
30 }
控制台程序的参数解析类库 CommandLine

3. 测试控制台程序

不输入任何参数,输出了参数的说明信息,如下图:

控制台程序的参数解析类库 CommandLine

输入参数,如下图:

控制台程序的参数解析类库 CommandLine

时间和字符串类型的字段都获取到了值。 

 
分类: C#