using MAX.Core.Commons; using System; using System.Diagnostics; using System.Text; namespace StoreHub.Framework.Helpers; public class WinCmdHelper { #region 执行Dos命令 /// /// 执行Dos命令 /// /// Dos命令及参数 /// 是否显示cmd窗口 /// 执行完毕后是否关闭cmd进程 /// 成功返回true,失败返回false public static Result ExcuteDosCommand(string cmd, string workdir, bool isShowCmdWindow = false, bool isWaitForExit = false, bool isCloseCmdProcess = true) { Result result = new(); try { StringBuilder errString = new(); StringBuilder outString = new(); Process p = new(); p.StartInfo.FileName = "cmd"; p.StartInfo.WorkingDirectory = workdir; p.StartInfo.Arguments = "/c " + cmd; p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.StartInfo.StandardErrorEncoding = Encoding.UTF8; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = !isShowCmdWindow; p.OutputDataReceived += new DataReceivedEventHandler(delegate (object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { outString.AppendLine(e.Data); Debug.WriteLine(e.Data); } }); p.ErrorDataReceived += new DataReceivedEventHandler(delegate (object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { errString.AppendLine(e.Data); } }); p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); if (isWaitForExit) { p.WaitForExit(); } if (isCloseCmdProcess) { p.Close(); } if (errString.Length <= 0) { result.Success = true; result.Data = outString.ToString(); } Console.WriteLine(string.Format("成功执行Dos命令[{0}]!", cmd)); return result; } catch (Exception ex) { Console.WriteLine("执行命令失败,请检查输入的命令是否正确:" + ex.Message, ex); result.Msg = ex.Message; } return result; } private static void P_ErrorDataReceived(object sender, DataReceivedEventArgs e) { throw new NotImplementedException(); } #endregion #region 判断指定的进程是否在运行中 /// /// 判断指定的进程是否在运行中 /// /// 要判断的进程名称,不包括扩展名exe /// 进程文件的完整路径 /// 存在返回true,否则返回false public static bool CheckProcessExists(string processName, string processFileName) { Process[] processes = Process.GetProcessesByName(processName); foreach (Process p in processes) { if (!string.IsNullOrEmpty(processFileName)) { if (processFileName == p?.MainModule?.FileName) { return true; } } else { return true; } } return false; } #endregion #region 结束指定的windows进程 /// /// 结束指定的windows进程,如果进程存在 /// /// 进程名称,不包含扩展名 /// 进程文件完整路径,如果为空则删除所有进程名为processName参数值的进程 public static bool KillProcessExists(string processName, string processFileName) { try { Process[] processes = Process.GetProcessesByName(processName); foreach (Process p in processes) { if (!string.IsNullOrEmpty(processFileName)) { if (processFileName == p.MainModule.FileName) { p.Kill(); p.Close(); } } else { p.Kill(); p.Close(); } } Console.WriteLine(string.Format("成功结束[{0}]进程!", processes)); return true; } catch (Exception ex) { Console.WriteLine("结束指定的Widnows进程异常:" + ex.Message, ex); return false; } } #endregion }