Finding user name of current logged in user using VB.NET
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
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
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