Kill Process By Name - C#

Kill Process By Name - C#

code snippet

c#
// Import System.Management assembly
public static void KillProcessByName(string processName, bool currentUserOnly = true)
        {
            try
            {
                string userName = "";
                if (currentUserOnly)
                {
                    userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                }
                var processFinder = new System.Management.ManagementObjectSearcher(string.Format("Select * from Win32_Process where Name Like '{0}'", processName));

                var processes = processFinder.Get();
                if (processes.Count == 0)
                    return;
                foreach (System.Management.ManagementObject managementObject in processes)
                {
                    var pId = Convert.ToInt32(managementObject["ProcessId"]);
                    var process = System.Diagnostics.Process.GetProcessById(pId);
                    if (currentUserOnly)
                    {
                        var processOwnerInfo = new object[2];
                        managementObject.InvokeMethod("GetOwner", processOwnerInfo);
                        var processOwner = (string)processOwnerInfo[0];
                        var net = (string)processOwnerInfo[1];
                        if (!string.IsNullOrEmpty(net))
                            processOwner = string.Format("{0}\\{1}", net, processOwner);
                        if (string.CompareOrdinal(processOwner, userName) == 0)
                            process.Kill();
                    }
                    else
                    {
                        process.Kill();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

"The secret of getting ahead is getting started"

Contact me!

Have questions? Feel free to use the form or send me an email with any questions.

I will be responsive to your requests and your questions.