0

I have been looking for a way to find the username associated with a specified process on widows 7 and above (if you open up task manager in the processes tab i want to provide image name to get back user name). This is not necessarily the current user.

Through my online search i found the following solution crop up a few times and it does pretty much exactly what i want:

Public Shared Sub Main()
    Dim selectQuery As SelectQuery = New SelectQuery("Win32_Process")
    Dim searcher As ManagementObjectSearcher = New
    ManagementObjectSearcher(selectQuery)
    For Each proc As ManagementObject In searcher.Get
    Console.WriteLine(proc("Name").ToString)
        Dim s(1) As String
        proc.InvokeMethod("GetOwner", CType(s, Object()))
        Console.WriteLine(("User: " & (s(1) + ("\\" + s(0)))))
    Next
    Console.ReadLine()
End Sub

The only issue i have is that this code only works for framework 4.5 and up. the application i'm currently developing is only 4.0 (not my choice unfortunately).

Does anyone have a framework 4.0 solution to this problem?

Thanks

Edit: OK, so it turns out I've been a bit of an idiot, everything used in the method above is supported in .net 4.0 (i forgot you have to use the drop down on MSDN to see the older supported versions).... i have added the system.management imports to my class however it does not seem to be recognizing the SelectQuery and ManagementObjectSearcher types... does anyone know how to solve this?

mattisrowe
  • 149
  • 2
  • 14
  • 1
    Do *not* ignore the return value of InvokeMethod(). Right now you have no idea when the method fails with, say, an Access Denied error. Which is a common enough mishap, the privileges of the user account that runs this code matter a great deal. – Hans Passant Oct 12 '15 at 11:40

2 Answers2

0

Following SO post may be useful. I have NOT used/tested it but the code sample should work as .NET Framework 4.0 was released on 2010-04-12 (wikipedia reference) and this SO post dates back to Apr 2009

how-do-i-determine-the-owner-of-a-process-in-c Apr 2009

Community
  • 1
  • 1
haraman
  • 2,744
  • 2
  • 27
  • 50
-1

Sorry just re-read your question and realised you are after a user for a specific process rather than the user for the application you are building so the below is not really applicable.

I will leave it here in case it is usefull for someone.

Try My.User.Name fairly sure this will do what you want, I don't have the ability to check it where I am but have used it on as far back as 3.5 I believe.

OSKM
  • 728
  • 14
  • 25