粉丝服务

一个跨平台执行外部命令的 C# 开源库

点击上方蓝字

关注我们

(本文阅读时间:5分钟)


转载自编程乐趣

对于我们程序员来说,在日常开发项目中,调用外部的命令是非常常见的,比如调用批处理命令、调用其他应用,这里面就涉及到进程的通讯、管理、启动、取消等一些操作,今天给大家推荐一个 C# 库,就可以满足这些日常的需求,避免重复造轮子。
这是基于 .NetCore 开发的 C# 库,一个用于与外部命令行界面交互的库,功能强大、使用简单的库。


技术架构

1、跨平台:这是基于 .NetCore 开发的系统,可以部署在 Docker、Windows、Linux、Mac;

2、支持 .NET Standard 2.0+、.NET Core 3.0+、.NET Framework 4.6.2+。




项目结构




项目特点

1、流畅的配置界面;
2、灵活的管道支持;
3、完全异步且支持取消的 API;
4、针对死锁提供解决方案;

5、支持中断信号支持取消。




使用方法

▍单个命令配置

var cmd = Cli.Wrap(\"git\")    .WithArguments(\"commit -m \\\"my commit\\\"\");

▍多命令配置

var cmd = Cli.Wrap(\"git\") .WithArguments(new[] {\"commit\", \"-m\", \"my commit\"});

▍多命令配置

var cmd = Cli.Wrap(\"git\") .WithArguments(args => args .Add(\"clone\") .Add(\"https://github.com/Tyrrrz/CliWrap\") .Add(\"--depth\") .Add(20) );

▍工作目录使用

var cmd = Cli.Wrap(\"git\") .WithWorkingDirectory(\"c:/projects/my project/\");

▍设置环境变量

var cmd = Cli.Wrap(\"git\") .WithEnvironmentVariables(new Dictionary<string, string?> { [\"GIT_AUTHOR_NAME\"] = \"John\", [\"GIT_AUTHOR_EMAIL\"] = \"john@email.com\" });

▍设置环境变量

var cmd = Cli.Wrap(\"git\") .WithEnvironmentVariables(env => env .Set(\"GIT_AUTHOR_NAME\", \"John\") .Set(\"GIT_AUTHOR_EMAIL\", \"john@email.com\") );

▍设置启动子进程的用户的域、名称和密码

var cmd = Cli.Wrap(\"git\") .WithCredentials(new Credentials( domain: \"some_workspace\", userName: \"johndoe\", password: \"securepassword123\", loadUserProfile: true ));

▍设置启动子进程的用户的域、名称和密码

var cmd = Cli.Wrap(\"git\") .WithCredentials(creds => creds .SetDomain(\"some_workspace\") .SetUserName(\"johndoe\") .SetPassword(\"securepassword123\") .LoadUserProfile() );

▍设置验证执行结果的策略

var cmd = Cli.Wrap(\"git\") .WithValidation(CommandResultValidation.ZeroExitCode);

▍管道流的使用

await using var input = File.OpenRead(\"input.txt\");await using var output = File.Create(\"output.txt\");
await Cli.Wrap(\"foo\") .WithStandardInputPipe(PipeSource.FromStream(input)) .WithStandardOutputPipe(PipeTarget.ToStream(output)) .ExecuteAsync();

▍Http 流

using var httpClient = new HttpClient();await using var input = await httpClient.GetStreamAsync(\"https://example.com/image.png\");
var cmd = input | Cli.Wrap(\"foo\");await cmd.ExecuteAsync();

  • 项目地址

    https://github.com/Tyrrrz/CliWrap

*未经授权请勿私自转载此文章及图片。

谢谢你读完了本文!欢迎在评论区留言分享你的想法,并且转发到朋友圈。

长按识别二维码

关注微软开发者MSDN


喜欢记得分享哦~

本栏目精选

热门推荐

频道导航