Get Process User Name
Recently I was developing a little one-off application for use on our home computer that I share with Erin. I was working on a library that would enable you to easily add items to the shell context menu in windows, so you could put your own custom context menu options onto specific file types.
In order to test the library out, I had to register the assembly using regasm.exe, then copy the assemblies to the GAC so explorer.exe could find them, and then I needed to restart explorer.exe, so that it would refresh the code. The problem came when I wanted to restart explorer, because we use fast user switching, so it was possible for Erin to have explorer.exe running, as well as myself, and I didn’t want to kill her instance of explorer, I wanted to kill mine. So I needed to know how to get the username of a process, because there isn’t a convenient Process.UserName property on the System.Diagnostics.Process class (don’t ask me why, I don’t get it either).
Anyways, a quick google search brought up some results, and I thought I would share them here. I found a vb solution on experts-exchange, and I ported this to c#, heres the code to get the username of a process, by process ID:
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”;
}
Of course, I come to find out later on that its a bad idea to write shell extensions in managed code, which makes sense when you think about it. Oh well, it was interesting work while it lasted