2013-04-08 56 views
0

我試圖啓動一個程序並閱讀它的標準輸出。但是這個事件從未被提出。 我開始的過程正在運行,並在控制檯中使用相同的參數創建輸出。 任何想法,我做錯了什麼?重定向標準輸出,事件不會上調

public void StartProcess(string Filename, string Arguments) 
    { 
     currentProcess = new Process(); 
     currentProcess.StartInfo.FileName = Programm; 
     currentProcess.StartInfo.Arguments = Arguments; 
     currentProcess.StartInfo.UseShellExecute = false; 
     currentProcess.StartInfo.RedirectStandardOutput = true; 
     currentProcess.StartInfo.RedirectStandardError = true; 
     currentProcess.OutputDataReceived += OutputReceivedEvent; 
     currentProcess.EnableRaisingEvents = true; 

     string path = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_Result.txt"; 
     LastResult = path; 
     resultfile = File.CreateText(path); 

     currentProcess.Start(); 
     currentProcess.BeginOutputReadLine(); 
     response.command = Command.ACK; 
     SendMessage(response); 

    } 
    private void OutputReceivedEvent(object sender, DataReceivedEventArgs e) 
    { 
     resultfile.WriteLine(e.Data); 
    } 

編輯:我剛剛發現了一些奇怪的東西:我開始的過程是mcast。如果我啓動其他類似ping的代碼,我的代碼工作得很好。所以mcast似乎做了一些有趣的事情!編輯2:所以下面的代碼正在工作,但只讀取特定大小的塊,如果寫入流的字節更少,甚至不會發生,也不會發生.ReadBlock也不會返回任何內容。

編輯3:所以更多的更新,問題是,mcast不刷新它的輸出流。我結束了寫我自己的工具,這工作得很好。

+0

什麼調試器說什麼? – 2013-04-08 08:14:08

+0

U應該調用函數?還是我想輕鬆? 'StartProcess(文件名,參數)' – 2013-04-08 08:14:43

+0

根據您啓動的過程,您可能只會收到StandardErrorOutput。嘗試註冊您的事件currentProcess.ErrorDataReceived以及。 – 2013-04-08 08:20:52

回答

0

根據您的過程,您可能還需要使用currentProcess.ErrorDataReceived,然後currentProcess.BeginErrorReadLine(),因爲有些進程只是重定向到一個輸出,而不是兩個。無論如何它值得嘗試。

因此,這將是這樣的:

public void StartProcess(string Filename, string Arguments) 
{ 
    currentProcess = new Process(); 
    currentProcess.StartInfo.FileName = Programm; 
    currentProcess.StartInfo.Arguments = Arguments; 
    currentProcess.StartInfo.UseShellExecute = false; 
    currentProcess.StartInfo.RedirectStandardOutput = true; 
    currentProcess.StartInfo.RedirectStandardError = true; 
    currentProcess.OutputDataReceived += OutputReceivedEvent; 
    currentProcess.ErrorDataReceived += ErrorReceivedEvent; 

    currentProcess.EnableRaisingEvents = true; 

    string path = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_Result.txt"; 
    LastResult = path; 
    resultfile = File.CreateText(path); 

    currentProcess.Start(); 
    currentProcess.BeginOutputReadLine(); 
    currentProcess.BeginErrorReadLine(); 
    response.command = Command.ACK; 
    SendMessage(response); 

} 
private void OutputReceivedEvent(object sender, DataReceivedEventArgs e) 
{ 
    resultfile.WriteLine(e.Data); 
} 

/*This second event handler is to prevent a lock occuring from reading two separate streams. 
Not always an issue, but good to protect yourself either way. */ 
private void ErrorReceivedEvent(object sender, DataReceivedEventArgs e) 
{ 
    resultfile.WriteLine(e.Data); 
}