using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; namespace Vinno.FIS.Sonopost.Common { public class ProcessHelper { /// /// 开启进程 /// /// /// /// public static int StartProcess(string processPath, string args = "") { if (!File.Exists(processPath)) { return 0; } int retryCount = 0; int processId; bool exist; do { var p = new Process { StartInfo = { FileName = processPath, CreateNoWindow = true, WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden, RedirectStandardInput = true, Verb = "runas", Arguments = args } }; p.Start(); processId = p.Id; var existApp = IsProcessExist(processId); exist = existApp != null; if (exist == false && retryCount < 5) { retryCount++; Thread.Sleep(1000); } } while (exist == false); return processId; } /// /// 结束进程 /// /// /// public static bool FinishProcess(int processId) { int count = 10; while (count > 0) { var existApp = IsProcessExist(processId); if (existApp != null) { count--; try { existApp.Kill(); } catch { } Thread.Sleep(100); } else { return true; } } return false; } /// /// 结束所有这名称进程 /// /// /// public static bool FinishProcessByName(string processName) { int count = 10; while (count > 0) { var existApps = Process.GetProcessesByName(processName).Where(x => x.ProcessName == processName); if (!existApps.Any()) { return true; } foreach (var item in existApps) { try { item.Kill(); } catch { } Thread.Sleep(100); } count--; } return false; } /// /// 检查进程是否存在 /// /// /// public static Process IsProcessExist(int processId) { try { var existApp = Process.GetProcessById(processId); if (existApp != null) { return existApp; } } catch (ArgumentException) { //ignore } return null; } /// /// 检查进程是否存在 /// /// /// public static bool IsProcessExistByName(string processName) { return Process.GetProcessesByName(processName).Any(x => x.ProcessName == processName); } /// /// 根据进程名得到唯一的进程Id /// /// /// public static int GetProcessIdByName(string processName) { var existProcesses = Process.GetProcessesByName(processName).Where(x => x.ProcessName == processName); if (existProcesses.Count() == 1) { return existProcesses.FirstOrDefault().Id; } else { return 0; } } } }