启动进程和杀进程helper类

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;

namespace Common
{
    public class ProcessEasyUtil
    {
        #region StartProcess
        public static Process StartProcess(string exeFileName)
        {
            return StartProcess(exeFileName, string.Empty, null);
        }

        public static Process StartProcess(string exeFileName, string joinSeperator = "", params string[] startArgs)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = exeFileName;
            startInfo.Arguments = (startArgs == null) ? "" : string.Join(joinSeperator, startArgs);
            startInfo.WindowStyle = ProcessWindowStyle.Normal;
            startInfo.WorkingDirectory = Path.GetDirectoryName(exeFileName);
            startInfo.CreateNoWindow = true;

            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                //设置启动动作,确保以管理员身份运行
                startInfo.Verb = "runas";
            }

            Process process = Process.Start(startInfo);
            process.WaitForExit();
            return process;
        }
        #endregion

        #region KillProcess
        public static void CloseProcess(Process process)
        {
            process.Close();
        }
        #endregion

        #region KillProcess
        public static void KillProcess(string processName)
        {
            var proArray = Process.GetProcessesByName(processName);
            foreach (var proItem in proArray)
            {
                KillProcess(proItem);
            }
        }

        public static void KillProcess(int processId)
        {
            Process process = Process.GetProcessById(processId);
            KillProcess(process);
        }

        public static void KillProcess(Process process)
        {
            process.Kill();
        }
        #endregion
    }
}

你可能感兴趣的:(C#~Helper类)