ms-accessvbams-access-2003

environ("username") versus advapi32.dll


I know there are at least 2 ways of retrieving the username in an Access application.

You can use the environ function:

environ("username")

And you can use GetUsername in advapi32.dll

Public Declare Function GetUserName& Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long)

s = String(l, Chr(32))
GetUserName s, l
username = Left$(s, l - 1)

Which one of the above methods is the safest to use? And why?

Perhaps some background info, the applications are used both on the local computers and remote desktops.


Solution

  • As Simon has said, Environ variables are open to manipulation, however some people also like to avoid the api calls, if this is the case then this is a simple to follow alternative:

    Public Function GetUser() As String
    
        Dim WNet As Object
    
        Set WNet = CreateObject("WScript.Network")
    
        GetUser = WNet.UserName
    
        Set WNet = Nothing
    
    End Function