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";
  }
 }
}