0

Possible Duplicate:
How do you kill a process for a particular user in .NET (C#)?

In my updater application i need to kill the main program before updating it.

Im using code to kill the process within the updater application, but it kills all processes with that name and therefore it kills the process for other users on the same machine. Is there some way to only kill the process for the current user?

This is my code so far:

        foreach (System.Diagnostics.Process myProc in System.Diagnostics.Process.GetProcesses())
        {
            if (myProc.ProcessName == "ProgramName")
            {
                myProc.Kill();
            }
        }
Community
  • 1
  • 1
alexy12
  • 515
  • 2
  • 5
  • 8
  • Never mind that you should be able to do better than killing a process like that: how are you going to update the binary if the process is still running for some other user? – Jon Jul 13 '12 at 07:54
  • 5
    looks like someone have asked the same thing at [here] (http://stackoverflow.com/questions/426573/how-do-you-kill-a-process-for-a-particular-user-in-net-c) – Ricky Jul 13 '12 at 07:54
  • Use `Process.GetProcessesByName("ProgramName")` instead of crawling all system processes. – Tisho Jul 13 '12 at 07:57

1 Answers1

0

you can achieve your requirement by using Windows Management Instrumentation (WMI), if you don't mind WMI

Example:

    System.Management.ManagementObjectSearcher Processes = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_Process Where Name ='notepad.exe' ");

    string user = "JohnDoe";
    foreach (System.Management.ManagementObject process in Processes.Get())
    {
        if (process["ExecutablePath"] != null)
        {
            string[] OwnerInfo = new string[2];
            process.InvokeMethod("GetOwner", (object[])OwnerInfo);

            if (OwnerInfo[0] == user)
            {
                process.Delete();
            }
        }
    }
HatSoft
  • 11,077
  • 3
  • 28
  • 43