2010-05-12 34 views
3

我正在尋找一種方式來從外部命令行應用程序中按字節讀取標準輸出字節。C# - 從外部命令行應用程序中按字節讀取標準輸出字節

當前的代碼有效,但僅當添加換行符時才起作用。有沒有一種方法可以逐字節讀取當前行輸入字節,這樣我就可以更新用戶進度。

例)

 
Proccesing file 

0% 10 20 30 40 50 60 70 80 90 100% 

|----|----|----|----|----|----|----|----|----|----| 

xxxxxx 

一個X在控制檯應用程序每隔幾分鐘添加,但不是在我的C#贏形式,因爲它僅更新時,它已經完成了與當前行(結束)

示例代碼:

Process VSCmd = new Process(); 
VSCmd.StartInfo = new ProcessStartInfo("c:\\testapp.exe"); 
VSCmd.StartInfo.Arguments = "--action run" 
VSCmd.StartInfo.RedirectStandardOutput = true; 
VSCmd.StartInfo.RedirectStandardError = true; 
VSCmd.StartInfo.UseShellExecute = false; 
VSCmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
VSCmd.StartInfo.CreateNoWindow = true; 

VSCmd.Start(); 

StreamReader sr = VSCmd.StandardOutput; 

while ((s = sr.ReadLine()) != null) 
{ 
    strLog += s + "\r\n"; 
    invoker.Invoke(updateCallback, new object[] { strLog }); 
} 


VSCmd.WaitForExit(); 

回答

2

嘗試使用StreamReader.Read()來讀取數據流的下一個可用字符,而不必等待全線。該函數返回一個int,即-1表示已到達流的末尾,否則可以將其轉換爲char

+0

感謝您的幫助! – RPS 2010-05-12 17:40:54

0

下面將逐個字符地建立strLog字符,我假設你想爲每行調用updateCallback,當然如果不是這種情況,那麼你可以刪除新行的檢查。

int currChar; 
    int prevChar = 0; 
    string strLog = string.Empty; 
    while ((currChar = sr.Read()) != -1) 
    { 
    strLog += (char)currChar; // You should use a StringBuilder here! 
    if (prevChar == 13 && currChar == 10) // Remove if you need to invoke for each char 
    { 
     invoker.Invoke(updateCallback, new object[] { strLog }); 
    } 

    prevChar = currChar; 
    }