我正在尝试在实时捕获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输出,当我尝试在CMD中运行Windows Defrag时除外。例如:如果我尝试输入像“Dir”这样的命令,它会实时读取输出,但是如果我尝试运行“Defrag C:/ f / u”之类的命令,它只会在完成后才读取输出操作。
知道如何让这个工作吗?谢谢。
答案 0 :(得分:0)
您需要使用多线程。创建一个新线程并将其传递给Outputstream处理程序,你就可以了。要测试是否需要多线程,请将其放在DefWork方法的开头:
MessageBox.Show(Line);