我正在尝试包括打开 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/