C# 如何在执行结束前从CMD中获取输出(命令="Defrag c: U")。

问题描述 投票:1回答:1

我在我的c#程序中调用Defrag.exe。我想获取更新后的碎片整理过程的输出。

我想把这个输出(红色矩形)打印在我的应用程序中(当11%的进度百分比更新时,它也应该被打印出来。) 。

enter image description here

我正在使用这段代码。

Process selectedProc = new Process();
selectedProc.StartInfo.UseShellExecute = false;
selectedProc.StartInfo.RedirectStandardOutput = true;
selectedProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
selectedProc.StartInfo.CreateNoWindow = true;

selectedProc.OutputDataReceived += (sender, e) => 
{                
       Debug.WriteLine(e.Data); 
};

selectedProc.StartInfo.WorkingDirectory = System.IO.Path.GetPathRoot(Environment.SystemDirectory);
selectedProc.StartInfo.FileName = System.IO.Path.Combine(Environment.SystemDirectory, "defrag.exe");
selectedProc.StartInfo.Arguments = "C: /U";
selectedProc.Start();
selectedProc.BeginOutputReadLine();

在一段时间后,我用这段代码关闭进程。

selectedProc.Kill();

在process.Start()和process.Kill()之间,我在Visual Studio的debug部分没有看到任何输出。甚至在defrag进程结束后也没有。问题出在哪里?

c# cmd output
1个回答
0
投票

你需要以管理员身份运行cmd并传递参数来运行碎片整理。

namespace System.IO.Defrag
{
    using System.Diagnostics;
    using System.Text.RegularExpressions;

    public class Defrag
    {
        private Process ownprocess;
public void Stop()
        {
            ownprocess?.Kill();
        }
        private IDictionary<Operations, string> vOperations = new Dictionary<Operations, string>()
        {
            {Operations.Analyze, "/A "},{ Operations.BootOptimize,"/B "},{ Operations.Defrag ,"/D "},
            {Operations.Optimize ,"/O "},{ Operations.FreespaceConsolidate,"/X "},{ Operations.PrintProgress,"/U "},
            {Operations.Retrim,"/L " },{ Operations.SlabConsolidate ,"/K "},{ Operations.TierOptimize,"/G "},
            {Operations.TrackProgress ,"/T "},{ Operations.Verbose,"/V"}
        };
        private IDictionary<Options, string> vOptions = new Dictionary<Options, string>()
        {
            {Options.MultiThread , "/M" },{ Options.MaxRuntime, "I"},{ Options.NormalPriority , "/H"},
            { Options.None,""}
        };
        public enum Options
        {
            NormalPriority,
            MaxRuntime,
            MultiThread,
            None
        }
        public enum Operations
        {
            Analyze,
            BootOptimize,
            Defrag,
            TierOptimize,
            SlabConsolidate,
            Retrim,
            Optimize,
            TrackProgress,
            PrintProgress,
            Verbose,
            FreespaceConsolidate
        }
        private string English = "437";
        public event DataReceivedEventHandler OutputData;

        public T GetValue<T>(string data)
        {
            object o = new object();
            T a = (T)o;
            if (a is string)
            {
                Regex he = new Regex(": (.*?)% ");
                var j = he.Match(data);
                o = j.Groups[1].Value;
                a = (T)o;
            }
            else if (a is int)
            {
                Regex he = new Regex(": (.*?)% ");
                var j = he.Match(data);
                o = Convert.ToInt32(j.Groups[1].Value);
                a = (T)o;
            }
            else if (a is double)
            {
                Regex he = new Regex(": (.*?)% ");
                var j = he.Match(data);
                o = Convert.ToDouble(j.Groups[1].Value);
                a = (T)o;
            }
            else
            {
                MessageBox.Show("This format is not supported.",$"Error 0x{Encoding.UTF8.GetBytes(a.GetType().Name).Length}",MessageBoxButton.OK,MessageBoxImage.Error);
            }
            return a;
        }
        private void cmd(string arg)
        {

            Process process = new Process();
            process.StartInfo = new ProcessStartInfo("cmd",$"/c start \"\" chcp {English} && start \"\" {arg}");
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            if (OutputData != null)
            {
                process.StartInfo.RedirectStandardOutput = true;
                process.OutputDataReceived += OutputData;
                ownprocess = process;
                process.Start();
                process.BeginOutputReadLine();
            }else
            {
                ownprocess = process;
                process.Start();

            }
        }
        public async void Start(string Volumes = "C:", Operations dOparations  = Operations.Defrag, Options options = Options.None)
        {
            await Task.Factory.StartNew(() => 
            {
                cmd($"defrag {Volumes} {vOperations[dOparations]}{vOptions[options]}");

            });
        }

    }

}
© www.soinside.com 2019 - 2024. All rights reserved.