繁体   English   中英

从 C# 调用 git-bash.exe 上的命令

[英]Invoke commands on git-bash.exe from C#

我正在尝试从 c# 启动 git-bash 并希望重定向inputStream以将命令发送到控制台窗口。

我对 cmd.exe 的某些操作做了同样的事情,但问题是 bash.exe 是 git-bash 进程的子进程

Task.Run(async () =>
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = false;
    startInfo.RedirectStandardInput = true;
    startInfo.RedirectStandardOutput = false;
    startInfo.FileName = @"C:\Program Files\Git\git-bash.exe";
    startInfo.WorkingDirectory = @"D:\git\workspace";
    try
    {
        using (Process exeProcess = Process.Start(startInfo))
        {
            using (StreamWriter sw = exeProcess.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    sw.WriteLine("echo I want to see this");
                    //sw.Flush() // I tried with and without FLush() no different
                }

                // Keep the Console open to see what happend
                while (true)
                {
                    await Task.Delay(400);
                }
            }
        }
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }
});

我找到了对我有用的东西。

// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = false;
startInfo.FileName = @"C:\Program Files\Git\git-bash.exe";
startInfo.WorkingDirectory = workspacePath;
startInfo.Arguments = "-c \"echo 'Hello World!';" +
                           "echo 'This is the next command!'; " +
                           "echo 'the last read keeps to shell open'; " +
                           "read\"";
try
{
   Process exeProcess = Process.Start(startInfo);
   exeProcess.WaitForExit();
}
catch ( Exception e)
{
   Debug.WriteLine(e.Message);
}

好处是我可以以完全相同的方式执行完全相同的步骤。 如果出现问题,我不必检查自己的设置、库或依赖项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM