我正在尝试实时捕获 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”这样的命令,它只会在完成后读取输出操作。
知道如何让它工作吗?谢谢你。