0
我正嘗試在CMD上實時捕獲輸出。我想讀取正在輸出的每一行。下面是我的代碼:Windows Defrag.exe上的實時CMD輸出
private void Defrag2()
{
string osDrive = Path.GetPathRoot(Environment.SystemDirectory);
Process Psi = new Process();
System.Text.Encoding SysEncoding = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage);
Psi.StartInfo = new ProcessStartInfo("cmd", @"/c defrag " + osDrive + " /a /u")
{
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
StandardOutputEncoding = SysEncoding,
StandardErrorEncoding = SysEncoding
};
Psi.EnableRaisingEvents = true;
Psi.OutputDataReceived += new DataReceivedEventHandler(OutPutDataRecieved);
Psi.Start();
Psi.BeginOutputReadLine();
}
void OutPutDataRecieved(object sender, DataReceivedEventArgs e)
{
this.DefStat(e.Data);
}
private void DefStat(string Line)
{
if (Line != null)
{
if (Line.Contains("do not need to def"))
{
defragstatustb.Invoke(new MethodInvoker(() => defragstatustb.Text = "You do not need to defrag this computer."));
}
if (defragRTB.InvokeRequired)
{ defragRTB.Invoke(new MethodInvoker(() => defragRTB.AppendText(Line + Environment.NewLine))); }
}
}
該代碼工作以及對捕獲CMD實時輸出,除了當我嘗試運行Windows的磁盤整理的CMD。例如:如果我嘗試輸入類似「Dir」的命令,它會實時讀取輸出,但是如果我嘗試運行諸如「Defrag C:/ f/u」之類的命令,它只會在完成後纔會讀取輸出操作。
任何想法如何得到這個工作?謝謝。
使用異步方法不應該是已經,因此就不需要多線程?我對你的意見有點困惑,請你再澄清一下如何把它放在多線程中? – 2012-08-11 23:17:37