2013-04-04 87 views
0

在我的項目(MVC 3)我想用下面的代碼運行外部控制檯應用程序:C#運行外部控制檯應用程序,並沒有ouptut?

string returnvalue = string.Empty; 

    ProcessStartInfo info = new ProcessStartInfo("C:\\someapp.exe"); 
    info.UseShellExecute = false; 
    info.Arguments = "some params"; 
    info.RedirectStandardInput = true; 
    info.RedirectStandardOutput = true; 
    info.CreateNoWindow = true; 

    using (Process process = Process.Start(info)) 
    { 
     StreamReader sr = process.StandardOutput; 
     returnvalue = sr.ReadToEnd(); 
    } 

,但我得到了returnvalue一個空字符串,該程序創建一個文件作爲一個結果,但有沒有創建任何文件。可能沒有執行Process

+1

是否可以通過管道將其輸出爲標準錯誤? – 2013-04-04 15:43:52

+0

您的IIS apppool用戶是否有足夠的權利? – 2013-04-04 15:44:14

+0

沒有足夠的信息。這裏沒有創建文件,你的問題也不清楚。 – 2013-04-04 15:45:58

回答

1

您必須等待您的外部程序完成,否則當您想要讀取它時,您想要讀取的輸出甚至不會生成。

using (Process process = Process.Start(info)) 
{ 
    if(process.WaitForExit(myTimeOutInMilliseconds)) 
    { 
    StreamReader sr = process.StandardOutput; 
    returnvalue = sr.ReadToEnd(); 
    } 
} 
+0

process.WaitForExit()這是一個void函數,而不是bool – Tony 2013-04-04 15:57:21

+0

thx!請參閱編輯:) – wonko79 2013-04-04 16:00:34

0

爲TimothyP中的評論稱,設置RedirectStandardError = true,然後通過process.StandardError.ReadToEnd()後,我得到錯誤信息內容

0

如果我沒有記錯,在同一時間閱讀這兩個標準錯誤和標準輸出,必須使用異步回調來實現:

var outputText = new StringBuilder(); 
var errorText = new StringBuilder(); 
string returnvalue; 

using (var process = Process.Start(new ProcessStartInfo(
    "C:\\someapp.exe", 
    "some params") 
    { 
     CreateNoWindow = true, 
     ErrorDialog = false, 
     RedirectStandardError = true, 
     RedirectStandardOutput = true, 
     UseShellExecute = false 
    })) 
{ 
    process.OutputDataReceived += (sendingProcess, outLine) => 
     outputText.AppendLine(outLine.Data); 

    process.ErrorDataReceived += (sendingProcess, errorLine) => 
     errorText.AppendLine(errorLine.Data); 

    process.BeginOutputReadLine(); 
    process.BeginErrorReadLine(); 
    process.WaitForExit(); 
    returnvalue = outputText.ToString() + Environment.NewLine + errorText.ToString(); 
} 
相關問題