2013-08-18 42 views
2

我想對MinGW的其他過程與這段代碼執行命令:如何使用C#從其他進程在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 Huntleys answer,我的解決方案看起來是這樣的(我用的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();    
} 

回答

1

我懷疑C#是在命令提示符啓動您的MinGW命令打交道時使用using聲明。你需要在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(); 
+0

如何在Windows上做到這一點? 你能提供一些代碼嗎? –

+0

感謝您的回答,它的工作原理。我用工作代碼更新了我的問題。 –

1

你應該做的

str.Flush(); 

所以你寫的命令被傳遞給進程。

也應與流

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

      exeProcess.WaitForExit(); 
     } 
    } 
+0

感謝您的回答,我已經嘗試過str.Flush()並沒有幫助。 –

相關問題