//************************************************************************ // author: yuzhengyang // date: 2018.4.27 - 2018.5.30 // desc: CMD 工具 // Copyright (c) yuzhengyang. All rights reserved. //************************************************************************ using Azylee.Core.DataUtils.StringUtils; using Azylee.Core.ThreadUtils.SleepUtils; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading.Tasks; namespace Azylee.Core.WindowsUtils.CMDUtils { public class CMDProcessTool { /// /// 创建cmd的进程 /// /// public static Process GetProcess(string verb = "RunAs") { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "cmd.exe"; startInfo.Arguments = @"/c C:\Windows\System32\cmd.exe"; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.Verb = verb; Process process = new Process(); process.StartInfo = startInfo; return process; } /// /// 开始运行CMD命令 /// /// /// 输出动作 public static void Execute(string cmd, Action output) { StreamReader reader = null; Process process = null; try { process = GetProcess(); process.Start(); process.StandardInput.AutoFlush = true; process.StandardInput.WriteLine(cmd); process.StandardInput.WriteLine("exit"); reader = process.StandardOutput; do { string line = reader.ReadLine(); output?.Invoke(line); } while (!reader.EndOfStream); process.WaitForExit(); process.Close(); } catch { } } /// /// 运行CMD并读取结果(建议执行返回数据较小的命令) /// /// /// public static List Execute(string cmd) { List result = null; StreamReader reader = null; Process process = null; try { process = GetProcess(); process.Start(); process.StandardInput.WriteLine(cmd); process.StandardInput.WriteLine("exit"); reader = process.StandardOutput; result = new List(); do { string line = reader.ReadLine(); if (Str.Ok(line)) result.Add(line.Trim()); } while (!reader.EndOfStream); process.WaitForExit(); } catch { } finally { reader?.Close(); process?.Close(); process?.Dispose(); } return result; } } }