Search for username for current user using VB.NET

I am trying to get the username of the current user. When I log in as Johnny Smith and run the application without administrator privileges, it will return me the correct Johnny Smith username. But the problem is that when I right-click and select "Run as administrator", Windows will offer me a login window for the administrator, and after logging in, my application will return the username admin , not the user who is logged in system now.

I tried:

 strUserLabel.Text = Environment.UserName 

Besides

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

Both return me the administrator username when prompted as administrator.

+6
source share
3 answers

I get it. I used this function, which will determine which process the user is using. In my code, I determined that I was looking for the user name 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 0 will return username

Index 1 will return the domain name of the user

+1
source

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

Before .NET 3

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

Starting with version 3

Gets the name of the user who is currently logged on to Windows.

+6
source

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, it takes 2+ seconds!

What about:

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

Tested in VS2017

0
source

Source: https://habr.com/ru/post/971226/


All Articles