…meie igapäevast IT’d anna meile igapäev…

2012-08-23

C#: kill process by name for the current user

Filed under: Programmeerimine — Sander @ 09:59:20
Tags: ,

Quite often there is a need to kill a specific process or several processes. While processes are easy to get with Process.GetProcessesByName(), Process class doesn’t give us the owner of the process, so we will invariably get processes for all users. We have to turn to WMI to get the owner of the process:

  1. ///<summary>
  2. /// Kill the processes specified by the name (“notepad.exe”)
  3. ///</summary>
  4. ///<param name=”processName”>Name of the process, case-insensitive.</param>
  5. ///<param name=”currentUserOnly”>If true, kill only processes by current user</param>
  6. public static void KillProcessByName(string processName, bool currentUserOnly = true)
  7. {
  8.     try
  9.     {
  10.         string userName = null;
  11.         if (currentUserOnly)
  12.         {
  13.             WindowsIdentity user = WindowsIdentity.GetCurrent();
  14.             if (user == null)
  15.                 throw new InvalidCredentialException(“No current user?!”);
  16.             userName = user.Name;
  17.         }
  18.         var processFinder = new ManagementObjectSearcher(string.Format(“Select * from Win32_Process where Name='{0}‘”, processName));
  19.         var processes = processFinder.Get();
  20.         if (processes.Count == 0)
  21.             return;
  22.         foreach (ManagementObject managementObject in processes)
  23.         {
  24.             var pId = Convert.ToInt32(managementObject[“ProcessId”]);
  25.             var process = Process.GetProcessById(pId);
  26.             if (currentUserOnly) //current user
  27.             {
  28.                 var processOwnerInfo = new object[2];
  29.                 managementObject.InvokeMethod(“GetOwner”, processOwnerInfo);
  30.                 var processOwner = (string)processOwnerInfo[0];
  31.                 var net = (string)processOwnerInfo[1];
  32.                 if (!string.IsNullOrEmpty(net))
  33.                     processOwner = string.Format(“{0}\\{1}”, net, processOwner);
  34.                 if (string.CompareOrdinal(processOwner, userName) == 0)
  35.                     process.Kill();
  36.             }
  37.             else //any user                    
  38.                 process.Kill();
  39.         }
  40.     }
  41.     catch (Exception ex)
  42.     {
  43.         //There is a good chance for UnauthorizedAccessException here, so
  44.         //log the error or handle otherwise
  45.     }
  46. }

You can easily modify the method not to work only with current user, but any user you specify – just make userName into a parameter. Or you can use this to return information about user having processes with that name – don’t use it as a replacement for Mutex or EventWaitHandle, though.

4 kommentaari »

  1. This code does not compile because of this:

    processOwner = string.Format(“{0}\\\cf6 {1}”, net, processOwner);

    Could you help, please?

    kommentaar kirjutas IRQ — 2013-04-02 @ 22:52:06 | Vasta

    • Seems that code highlighter plugin had mangled escape sequence/character – it should be “string.Format(“{0}\\{1}”, net, processOwner);”. Fixed in the post now, too – thank you for notifying me!

      kommentaar kirjutas Sander — 2013-04-03 @ 10:05:07 | Vasta

      • Ok, thanks. I supposed there should not be anything except {0}\\{1} so that it is merely machinname\username format.

        Thanks for the article, it helped me!

        kommentaar kirjutas IRQ — 2013-04-03 @ 12:16:24 | Vasta

  2. Line 20 should be
    var processFinder = new ManagementObjectSearcher(string.Format(“Select * from Win32_Process where Caption=’{0}‘”, processName));

    kommentaar kirjutas gfeng — 2013-08-07 @ 18:22:59 | Vasta


RSS feed for comments on this post. TrackBack URI

Lisa kommentaar

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Muuda )

Twitter picture

You are commenting using your Twitter account. Log Out / Muuda )

Facebook photo

You are commenting using your Facebook account. Log Out / Muuda )

Google+ photo

You are commenting using your Google+ account. Log Out / Muuda )

Connecting to %s

Create a free website or blog at WordPress.com.