NetCore控制台实现自定义CommandLine功能

命令行科普:

例如输入: trans 123 456 789 -r 123 -r 789
上面例子中:trans是Command,123 456 789是CommandArgument,-r之后的都是CommandOption.注意:命令行的格式是固定的
Command是必须的,CommandArgument和CommandOption都是可选的
只有设置了CommandArgument的multipleValues为true后,CommandArgument才可以接受多个参数,单个参数和多个参数可以通过CommandArgument.Values获取
CommandOption设置了MultipleValue之后输入格式必须为-option optionvalue -option optionvalue...

NetCore插件:McMaster.Extensions.CommandLineUtils,项目源码:https://github.com/natemcmaster/CommandLineUtils

1、新建一个控制台项目

2、管理Nuget包。添加McMaster.Extensions.CommandLineUtils的引用

3、写代码

 1 using System;
 2 using System.Threading.Tasks;
 3 
 4 namespace Tree
 5 {
 6     class Program
 7     {
 8         static void Main(string[] args)
 9         {
10             CommandLine line = new CommandLine();
11             line.Run(args);
12         }
13     }
14 }
View Code
 1 using McMaster.Extensions.CommandLineUtils;
 2 
 3 namespace Tree
 4 {
 5     public class CommandLine
 6     {
 7         public void Run(string[] args)
 8         {
 9             CommandLineApplication app = new CommandLineApplication(false);
10             app.HelpOption("-?|-h|--help");
11             app.OnExecute(() =>
12             {
13                 app.ShowHelp();
14                 return 0;
15             });
16             app.Command("trans", command =>
17             {
18                 //var args1 = new[] { "Arg1", "arg with space", "args ' with \" quotes" };
19                 //Process.Start("echo", ArgumentEscaper.EscapeAndConcatenate(args1));
20                 string password = Prompt.GetPassword("please input your password: ");
21                 //Process.Start(DotNetExe.FullPathOrDefault(), "run");
22                 CommandArgument argument = command.Argument("[name]", "", multipleValues: true);
23                 CommandOption option = command.Option("-t", "this is a template", CommandOptionType.NoValue);
24                 command.OnExecute(() =>
25                 {
26                     if (option.Value() == "-t")
27                     {
28                         bool isRun = Prompt.GetYesNo("confirm your transaction, do your want to continue:", false);
29                         if (!isRun)
30                         {
31                             return;
32                         }
33                         command.Out.WriteLine($"密码是{password}, 参数是:{argument}");
34                         return;
35                     }
36                 });
37             });
38             app.Execute(args);
39         }
40     }
41 }
View Code

4、结果

转载于:https://www.cnblogs.com/wangyulong/p/9296164.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值