Finding user name of current logged in user using VB.NET

42,244

Solution 1

I have figured it out. I used this function which will determine which process which the user is using. In my code I defined that look for username of the explorer.exe process.

Function GetUserName() As String

    Dim selectQuery As Management.SelectQuery = New Management.SelectQuery("Win32_Process")
    Dim searcher As Management.ManagementObjectSearcher = New Management.ManagementObjectSearcher(selectQuery)
    Dim y As System.Management.ManagementObjectCollection
    y = searcher.Get

    For Each proc As Management.ManagementObject In y
        Dim s(1) As String
        proc.InvokeMethod("GetOwner", CType(s, Object()))
        Dim n As String = proc("Name").ToString()
        If n = "explorer.exe" Then
            Return s(0)
        End If
    Next
End Function

Index of 0 will return username

Index of 1 will return domain name of user

Solution 2

In the MSDN documentation, I discovered they changed the definition of property Environment.UserName.

Before .NET 3

Gets the user name of the person who started the current thread.

Starting from version 3

Gets the user name of the person who is currently logged on to the Windows operating system

Solution 3

I think the accepted answer above is a VERY resource intensive way to find a username. It has nested loops with hundreds of items. In my 8GP RAM PC this takes 2+ seconds!

How about:

  • Username: SystemInformation.Username, and
  • DomainName: Environment.UserDomainName

Tested in VS2017

Share:
42,244
Mario LIPCIK
Author by

Mario LIPCIK

Updated on July 29, 2022

Comments

  • Mario LIPCIK
    Mario LIPCIK almost 2 years

    I'm trying to get the user name of the current user. When I log in as Johnny Smith and run my application without administrator privileges it will return me the correct user name, Johnny Smith. But the problem is that when I right click and choose "Run as Administrator", Windows will prompt me with a login screen for the administrator and after login my application returns user name admin, not the user which is logged in currently.

    I have tried:

    strUserLabel.Text = Environment.UserName
    

    Also

    Dim WSHNetwork = CreateObject("WScript.Network")
    Dim strUser = ""
    
    While strUser = ""
        strUser = WSHNetwork.Username
    End While
    
    strUserLabel.Text = strUser
    

    Both return me the administrator user name when prompted as administrator.