SouthL
SouthL

Reputation: 175

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.

Upvotes: 3

Views: 6276

Answers (2)

Matt Donnan
Matt Donnan

Reputation: 5003

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

Upvotes: 6

Simon Richter
Simon Richter

Reputation: 29618

Environment variables can be set and unset by anyone, go missing and whatnot, and these cases tend to be difficult to reproduce if anyone even thinks of it as a source of errors.

I'd definitely go with advapi.

Upvotes: 2

Related Questions