REAL TIMEで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 Defrag を実行しようとする場合を除いて、リアルタイムでの CMD 出力のキャプチャでうまく機能します。例: 「Dir」のようなコマンドを入力しようとすると、リアルタイムで出力が読み取られますが、「Defrag C: /f /u」のようなコマンドを実行しようとすると、完了後にのみ出力が読み取られます。操作。
これを機能させる方法はありますか?ありがとうございました。