首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Windows Defrag.exe上的实时命令输出

Windows Defrag.exe上的实时命令输出
EN

Stack Overflow用户
提问于 2012-08-12 05:53:28
回答 1查看 452关注 0票数 0

我正在尝试实时捕获CMD上的输出。我想要读取输出的每一行。以下是我的代码:

代码语言:javascript
复制
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碎片整理时,该代码在实时捕获CMD输出方面工作得很好。例如:如果我尝试输入像"Dir“这样的命令,它会实时读取输出,但是如果我尝试运行像"Defrag C: /f /u”这样的命令,它只会在完成操作后才读取输出。

你知道怎么让它工作吗?谢谢。

EN

回答 1

Stack Overflow用户

发布于 2012-08-12 06:42:00

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

代码语言:javascript
复制
MessageBox.Show(Line);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11917954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档