Library code snippets

Get Current Username in VB.NET

This code demonstrates how to retrieve the username of the current windows user in VB.NET

   Declare Function GetUserName Lib "advapi32.dll" Alias _
       "GetUserNameA" (ByVal lpBuffer As String, _
       ByRef nSize As Integer) As Integer

   Public Function GetUserName() As String
       Dim iReturn As Integer
       Dim userName As String
       userName = New String(CChar(" "), 50)
       iReturn = GetUserName(userName, 50)
       GetUserName = userName.Substring(0, userName.IndexOf(Chr(0)))
   End Function

Comments

  1. 08 Feb 2006 at 00:16

    Environment.Username returns the name of the user running the current process.


    If the current process is running under the System/LocalService/NetworkService accounts, it would just give you one of these rather than the logged-in user.

  2. 08 Feb 2006 at 00:15

    Environment.Username returns the name of the user running the current process.


    If the current process is running under the System/LocalService/NetworkService accounts, it would just give you one of these rather than the logged-in user.

  3. 24 Jan 2005 at 03:49


    Imports System.Security
    Imports System.Security.Principal.WindowsIdentity


    After Importing the above


    Add this to a click event of the button.


    MsgBox(GetCurrent.Name)



  4. 08 Nov 2004 at 17:19

    Environ("username") does not work in non Domain OS's (95/98).  Alternate code is required.

  5. 02 May 2004 at 19:54

    You could more easily get the username by just typing:


    CONSOLE.WRITELINE(ENVIRONMENT.USERNAME)


    One line of code gets the current username. No controls, nothing else needed, just the reference to the System Class. Place the line of code in Sub Main() and that is all you need.

  6. 01 Jan 1999 at 00:00

    This thread is for discussions of Get Current Username in VB.NET.

Leave a comment

Sign in or Join us (it's free).

Walter Steed

Related podcasts

  • xpert to Expert: Inside Concurrent Basic (CB)

    "Concurrent Basic extends Visual Basic with stylish asynchronous concurrency constructs derived from the join calculus. Our design advances earlier MSRC work on Polyphonic C#, Comega and the Joins Library. Unlike its C# based predecessors, CB adopts a simple event-like syntax familiar to VB progr...

We'd love to hear what you think! Submit ideas or give us feedback