【问题标题】:Real Time CMD Output on Windows Defrag.exeWindows Defrag.exe 上的实时 CMD 输出
【发布时间】:2012-08-11 21:53:27
【问题描述】:

我正在尝试实时捕获 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”这样的命令,它只会在完成后读取输出操作。

知道如何让它工作吗?谢谢。

【问题讨论】:

    标签: c# .net visual-studio-2010 console cmd


    【解决方案1】:

    您需要使用多线程。创建一个新线程并将其传递给 Outputstream 处理程序,您就可以开始了。要测试是否需要多线程,请将其放在 DefWork 方法的开头:

    MessageBox.Show(Line);
    

    【讨论】:

    • 不应该已经在使用异步方法,因此不需要多线程?我对您的说法有些困惑,请您进一步说明如何将其放入多线程中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    相关资源
    最近更新 更多