c# - 如何通过c#代码打开和使用Git Bash

标签 c# windows git git-bash

我正在尝试包括打开 Git Bash、 push 和 pull 入我的 c# 代码。使用 Process.Start() 打开 Git Bash 时不是问题,我无法将命令写入 Git Bash。

我试过在 ProcessStartInfo.Arguments 中包含命令,以及重定向标准输出。两者都没有奏效。在下面,您可以看到我尝试过的不同代码片段。

private void Output()
{
    //Try 1
    processStartInfo psi = new ProcessStartInfo();
    psi.FileName = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Git\Git Bash.lnk";
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;
    psi.Argument = "git add *";
    Process p = Process.Start(psi);
    string strOutput = p.StandardOutput.ReadToEnd();
    Console.WriteLine(strOutput);

    //Try 2
    ProcessStartInfo psi = new ProcessStartInfo(@"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Git\Git Bash.lnk");
    Process.Start(psi);
    psi.Arguments = "git add *";
    Process.Start(psi);

    //Try 3
    var escapedArgs = cmd.Replace("\"", "\\\"");
    var process = new Process()
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = @"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Git\Git Bash.lnk",
            Arguments = "cd C:\\Users\\strit\\autocommittest2\\autocommittest2\n",
             RedirectStandardOutput = true,
             UseShellExecute = false,
             CreateNoWindow = true,
         }
    };
    process.Start();
    string result = process.StandardOutput.ReadToEnd();
    process.WaitForExit();
}

Git Bash 打开但没有在命令行中写入任何内容。

最佳答案

我知道这是个老问题,仍在添加答案,因为几天前我也遇到了同样的问题。

我想你缺少的是-c范围。我使用了下面的代码,它解决了这个问题。 -c告诉 git-bash 执行以下内容,类似于 -cmd命令行中的参数。

在下面提到的功能中 -
fileName = git-bash.exe 的路径。
command = 要执行的 git 命令。
workingDir = git 存储库的本地路径。

public static void ExecuteGitBashCommand(string fileName, string command, string workingDir)
{

    ProcessStartInfo processStartInfo = new ProcessStartInfo(fileName, "-c \" " + command + " \"")
    {
        WorkingDirectory = workingDir,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        RedirectStandardInput = true,
        UseShellExecute = false,
        CreateNoWindow = true
    };

    var process = Process.Start(processStartInfo);       
    process.WaitForExit();

    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();
    var exitCode = process.ExitCode;

    process.Close();
}

我希望它能解决问题。

关于c# - 如何通过c#代码打开和使用Git Bash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55353264/

相关文章:

c# - ASP.net 中的浏览器滚动条(如何设置)

c# - VB连接数据库出错

c++ - 使用 C++ 的全局键盘钩子(Hook)

node.js - 无法在Windows上npm安装react-native

git - 如何为Git同步操作指定ppk?

wordpress - github上的公共(public)密码

c# - WPF WebBrowser 控件中的 ckeditor

c# - 为什么可以在类中编写 dispose() 方法时使用 IDisposable

c# - 免注册 com dll 要求安装 .net Framework 3.5,而注册后它工作正常

协程:如何判断 Windows Fiber 是否已完成执行?