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

时间:2023-03-08 15:47:17

命令行科普:

例如输入: 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、写代码

 using System;
using System.Threading.Tasks; namespace Tree
{
class Program
{
static void Main(string[] args)
{
CommandLine line = new CommandLine();
line.Run(args);
}
}
}
 using McMaster.Extensions.CommandLineUtils;

 namespace Tree
{
public class CommandLine
{
public void Run(string[] args)
{
CommandLineApplication app = new CommandLineApplication(false);
app.HelpOption("-?|-h|--help");
app.OnExecute(() =>
{
app.ShowHelp();
return ;
});
app.Command("trans", command =>
{
//var args1 = new[] { "Arg1", "arg with space", "args ' with \" quotes" };
//Process.Start("echo", ArgumentEscaper.EscapeAndConcatenate(args1));
string password = Prompt.GetPassword("please input your password: ");
//Process.Start(DotNetExe.FullPathOrDefault(), "run");
CommandArgument argument = command.Argument("[name]", "", multipleValues: true);
CommandOption option = command.Option("-t", "this is a template", CommandOptionType.NoValue);
command.OnExecute(() =>
{
if (option.Value() == "-t")
{
bool isRun = Prompt.GetYesNo("confirm your transaction, do your want to continue:", false);
if (!isRun)
{
return;
}
command.Out.WriteLine($"密码是{password}, 参数是:{argument}");
return;
}
});
});
app.Execute(args);
}
}
}

4、结果

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