如何使用C#从其他进程运行Mingw命令?

3
我正在尝试使用以下代码从其他进程在Mingw上执行命令:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"PATH-TO-MINGW\mingwenv.cmd";        
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;

using (Process exeProcess = Process.Start(startInfo))
{                
   StreamWriter str = exeProcess.StandardInput;
   str.WriteLine("ls");               

   exeProcess.WaitForExit();
}

但这段代码只是启动了Mingw,没有输入命令。
我错过了什么还是不可能做到?
谢谢。
更新
根据Jason Huntley的答案,对于我来说,解决方案如下(我正在使用OMNeT++模拟器,因此目录是基于它的)。
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"PATH_TO_SIMULATOR\omnetpp-4.3\msys\bin\sh.exe";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
using (Process exeProcess = Process.Start(startInfo))
{
   using (StreamWriter str = exeProcess.StandardInput)
   {
       str.WriteLine("cd PATH_TO_SIMULATOR/omnetpp-4.3");
       str.Flush();

       str.WriteLine("ls");
       str.Flush();
   }         

   exeProcess.WaitForExit();               
}
2个回答

2
我猜测c#正在CMD提示符中启动您的mingw命令。您需要在bash shell中生成进程。尝试用"bash -l -c 'ls'"或"bash -c'ls'"包装您的命令。确保bash在您的PATH中,并确保引用命令参数(如果有)。当我从python中的popen生成bash命令时,我不得不使用这种方法。我知道语言不同,但可能相关。
我想象代码看起来会像这样。我还没有在C#中测试过:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "bash.exe";
startInfo.Arguments = "-l -c 'ls -l /your/msys/path'";
# Or other examples with windows path:
#   startInfo.Arguments = "-l -c 'ls -l /c/your/path'";
#   startInfo.Arguments = "-l -c 'ls -l C:/your/path'";
#   startInfo.Arguments = "-l -c 'ls -l C:\\your\\path'";
process.StartInfo = startInfo;
process.Start();

谢谢回答,它有效。我已经更新了我的问题,并附上了可行的代码。 - Samvel Siradeghyan

1
你应该做。
str.Flush();

所以你编写的命令已被传递给进程。

在处理流时,还应使用using语句。

     using (Process exeProcess = Process.Start(startInfo))
     {
        using(StreamWriter str = exeProcess.StandardInput)
        {
           str.WriteLine("ls");
           str.Flush();

           exeProcess.WaitForExit();
        }
     }

谢谢回答,我已经尝试了str.Flush(),但没有起到作用。 - Samvel Siradeghyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接