c# - 如何通过c#代码打开和使用Git Bash
问题描述
我正在尝试包括打开 Git Bash,推入和拉入我的 c# 代码。虽然打开 Git BashProcess.Start()
不是问题,但我无法将命令写入 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();
}
我希望它能解决问题。
推荐阅读
- sql - RESET SUM(AMT_FIELD) OVER(PARTITION BY UNIQUE FIELD ORDER BY ROWNUM)
- python - 设置TensorFlow的路径
- html - 导航栏不适用于特定主页 | 恩金
- javascript - 如何判断一个事件是否调用了“stopImmediatePropagation()”?
- mysql - 将 5.1 升级到 5.7 后,mysql 在 CentOS 6.9 中无法启动
- visual-studio-code - 如何与 VS Code 稳定版和内部版本共享扩展和设置?
- laravel - Laravel Foreach 循环
- tensorflow - `tf.data.Dataset.map` 是否保留输入顺序?
- ruby-on-rails - 如何在 CSV 导入中自动设置某些行值到 Ruby on Rails 应用程序中
- python - 在 GCP 上运行时出错:意外的关键字参数“maximum_iterations”