Get List of Process with Process Owner/User

Recently I have come to a situation where I want to list all the process in the computer. Solution was quite simple using Process.GetProcess().

Process[] processlist = Process.GetProcesses();
 
foreach (Process theprocess in processlist)
{
 Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}


However I also want to see that process is created with which user. For this after some googling, I found this solution. Hopefully it will be useful for you happy coding !!!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;
 
namespace ProcessViewer
{
 class Program
 {
  static void Main(string[] args)
  {
   GetProcessInfo();
  }
 
  /// Gets the process info.
  static void GetProcessInfo()
  {
   foreach (var process in Process.GetProcesses())
   {
    string name = process.ProcessName;
    int processId = process.Id;
    string windowTitle = process.MainWindowTitle ?? "N/A";
 
    Console.Out.WriteLine(string.Format("{0,20}|{1,10}|{2,20}|{3,20}",
     name,
     processId,
     GetProcessOwner(processId),
     windowTitle));
   }
   Console.ReadKey();
  }
 
  /// Gets the process owner.
  static string GetProcessOwner(int processId)
  {
   string query = "Select * From Win32_Process Where ProcessID = " + processId;
   ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(query);
   ManagementObjectCollection moCollection = moSearcher.Get();
 
   foreach (ManagementObject mo in moCollection)
   {
    string[] args = new string[] { string.Empty };
    int returnVal = Convert.ToInt32(mo.InvokeMethod("GetOwner", args));
    if (returnVal == 0)
     return args[0];
   }
 
   return "N/A";
  }
 }
}

2 comments:

  1. I seriously love youг website.. Pleasant colorѕ & theme.
    Did you build this site уоurself? Please replу back as І'm hoping to create my own site and would love to learn where you got this from or just what the theme is named. Cheers!Watch The Clone Wars Season 5 Episode 9 Online
    Also visit my website ... The Clone Wars Season 5 Episode 9 Free Stream

    ReplyDelete
  2. Water Hack Burns 2lb of Fat OVERNIGHT

    At least 160 000 women and men are utilizing a easy and secret "liquids hack" to lose 1-2 lbs each night in their sleep.

    It's proven and it works with anybody.

    Just follow these easy step:

    1) Go get a glass and fill it half the way

    2) Proceed to learn this weight losing HACK

    and become 1-2 lbs lighter in the morning!

    ReplyDelete