c# – How to kill a process of a specific user on Windows Server?


I have a C# application that in the end needs to kill a process of the user that ran it, but as I'm on a Terminal Server (Windows Server) and there are several logged in users, when I put the command to kill the process

Process[] processo = Process.GetProcessesByName("IEDriverServer");

    foreach (Process process in processo)
        process.Kill();// finaliza processo

It kills all users logged into the Terminal Server (Windows Server), is there any way to kill only the process of the user who ran my application?


According to this answer in the SO you can do this:

Process[] processlist = Process.GetProcesses();
bool rdpclipFound = false;
foreach (Process theprocess in processlist) {
    String ProcessUserSID = GetProcessInfoByPID(theprocess.Id);
    String CurrentUser = WindowsIdentity.GetCurrent().Name.Replace("SERVERNAME\\",""); 
    if (theprocess.ProcessName == "rdpclip" && ProcessUserSID == CurrentUser) {
        rdpclipFound = true;
if (rdpclipFound) {
   MessageBox.Show("rdpclip.exe successfully restarted");
} else {
   MessageBox.Show(@"rdpclip was not running under your username.
       It has been started, please try copying and pasting again.");

I put it on GitHub for future reference .

Obviously it needs some adaptations. There it is fixed what the process is. But I think I could see where it takes the user's information and compares it to know if it's the user's or not and if it should kill him. There is another answer that doesn't use the current user. And it has a link to other solutions.

Another solution closer to what you need with another approach in another answer in OS .

static void KillProcessByNameAndUserName(string processName, string userName) {
    var processes = from p in Process.GetProcessesByName(processName)
                    where GetProcessOwner(p.Id) == userName
                    select p;
    foreach(Process p in processes) p.Kill();

static string GetProcessOwner(int processId) {
    string query = “Select * From Win32_Process Where ProcessID = “ + processId;
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    ManagementObjectCollection processList = searcher.Get();
    foreach (ManagementObject obj in processList) {
        string[] argList = new string[] { string.Empty };
        int returnVal = Convert.ToInt32(obj.InvokeMethod(“GetOwner”, argList));
        if (returnVal == 0)
            return argList[0];
    return “NO OWNER”;

I put it on GitHub for future reference .

Scroll to Top