Skip to content

C# 调用命令行工具

Published: at 18:43

如何使用C#调用git命令?

第一步,如何在 C# 中调用命令行工具?

static class CmdHelper
{
public static bool ExecuteTool(string toolFile, string args, out string result, out string errorMsg)
{
bool success = false;
string msg = string.Empty;
string errMsg = string.Empty;
try
{
Process p;
ProcessStartInfo psi;
psi = new ProcessStartInfo(toolFile);
psi.Arguments += args;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true; //允许重定向标准输出
psi.CreateNoWindow = true;
psi.RedirectStandardError = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
p = Process.Start(psi);
msg = p.StandardOutput.ReadToEnd(); //Call ReadToEnd() before WaitForExit()
p.WaitForExit();
success = p.ExitCode == 0;
if (!success)
{
StringBuilder sb = new StringBuilder();
sb.Append(p.StandardError.ReadToEnd());
errMsg = sb.ToString();
}
p.Close();
}
catch (Exception ex)
{
errMsg = ex.Message + " when invoke " + toolFile;
return false;
}
finally
{
result = msg;
errorMsg = errMsg;
}
return success;
}
}

参考资料:Process.StandardOutput使用注意事项(转)

第二步,找到git.exe的位置,调用之

通过命令调用git命令,需要带上 git-dir work-tree 两个参数。

具体的使用示例,可以看这里

完了~


原文链接: https://blog.jgrass.cc/posts/csharp-command-line-tools/

本作品采用 「署名 4.0 国际」 许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。