首页 > Windows开发 > 详细

c# 调用CMD命令并获取输出结果

时间:2019-11-27 12:16:03      阅读:537      评论:0      收藏:0      [点我收藏+]

 private static string CMDPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\cmd.exe";

 public static void RunCMDCommand(string Command, out string OutPut)
        {
            using (Process pc = new Process())
            {
                Command = Command.Trim().TrimEnd('&') + "&exit";

                pc.StartInfo.FileName = CMDPath;
                pc.StartInfo.CreateNoWindow = true;
                pc.StartInfo.RedirectStandardError = true;
                pc.StartInfo.RedirectStandardInput = true;
                pc.StartInfo.RedirectStandardOutput = true;
                pc.StartInfo.UseShellExecute = false;

                pc.Start();

                pc.StandardInput.WriteLine(Command);
                pc.StandardInput.AutoFlush = true;

                OutPut = pc.StandardOutput.ReadToEnd();
                int P = OutPut.IndexOf(Command) + Command.Length;
                OutPut = OutPut.Substring(P, OutPut.Length - P - 3);
                pc.WaitForExit();
                pc.Close();
            }
        }

使用:
RunCMDCommand("wmic cpu get name", out string cpuInfo);
cpuInfo = cpuInfo.Replace("Name", "").Replace("\n", "").Trim();

c# 调用CMD命令并获取输出结果

原文:https://www.cnblogs.com/bqh10086/p/11940454.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!