0

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」のようなコマンドを実行しようとすると、完了後にのみ出力が読み取られます。操作。

これを機能させる方法はありますか?ありがとうございました。

4

1 に答える 1

0

マルチスレッドを使用する必要があります。新しいスレッドを作成し、それを Outputstream ハンドラに渡すと、準備完了です。マルチスレッドが必要かどうかをテストするには、これを DefWork メソッドの先頭に置きます。

MessageBox.Show(Line);
于 2012-08-11T22:41:59.543 に答える