Jump to content


Get Username of Logged on User


  • Please log in to reply
1 reply to this topic

#1 Dylan

Dylan

    Advanced Member

  • Root Admin
  • PipPipPip
  • 1,060 posts
  • Location:Atlanta, GA, USA
  • Interests:Computer Science, Operating Systems

  • VB Knowledge: Experienced
  • VB Version:VB 2008 (.NET 3.0/3.5)
  • OS: Mac OS X

Posted 24 June 2007 - 11:44 PM

Ok, I'm going to show you how you can get the current logged on user in your application without the use of WMI or WinAPI!

For starters, we will need to get the raw data. This being the raw user name data.
Dim rName As String = My.User.Name
This will return our unformatted string with the domain of the user such as "ComputerName\UserName"

We will now need to format our string to get the correct values.
Dim lSlash As Integer = rName.LastIndexOf("\")
Dim fName As String = rName.Substring(lSlash + 1)
In this case, we will be using String.LastIndexOf. We will then add one (1) to the lSlash integer to give us the correct user name. The string named fName now holds are user name.

Your final code should look like this:
Dim rName As String = My.Computer.Name
Dim lSlash As Integer = rName.LastIndexOf("\")
Dim fName As String = rName.Substring(lSlash + 1)
MsgBox(fName)
I decided to show a message box with the logged on user's name. You can do whatever you would like with fName.

#2 programmer-in-training

programmer-in-training

    Experienced Member

  • Mods
  • PipPipPip
  • 1,955 posts
  • Gender:Male
  • Interests:Desktop/web programming, higher math, piano

  • VB Knowledge: Guru
  • VB Version:Other
  • OS: Windows 7 x64

Posted 06 September 2008 - 09:02 AM

You can also use Environment.UserName for the username only (i.e. without the domain), and Environment.UserDomainName to find the domain.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users