I have searched everywhere I can for a solution to this, and the code listed by others does not seem to work.
Background: I want to obtain the user's username using VB (Using Visual Studio 2008). I've done this in Excel VBA before, but the code used before doesn't work.
I've tried code listed on the MS site here: http://support.microsoft.com/kb/152970
and slightly varied code found here: http://www.developerfusion.com/code/4409/get-current-username-in-vbnet/
There are two issues with the code on the MS site:
Dim lpBuff As String * 25 isn't recognised - it says, end of expression expected after 'string', as if '* 25' is not recognised; and,
When I remove '* 25', I get an 'access violation' on the line: ret = GetUserName(lpBuff, 25)
Declare Function GetUserName Lib "advapi32.dll" Alias _ "GetUserNameA" (ByVal lpBuffer As String, _ ByRef nSize As Integer) As Integer Public Function ReturnUserName() As String ' Dimension variables Dim lpBuff As String * 25 Dim ret As Long, UserName As String ret = GetUserName(lpBuff, 25) ReturnUserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1) End Function
Can anyone suggest what I'm doing wrong?
Why don't you use
Environment.UserName
The Environment class contains numerous properties that map directly to base WinApi calls.
If I am not mistaken, Username maps to GetUserName as you can see from this decompiled code
public static string UserName
{
[SecuritySafeCritical]
get
{
new EnvironmentPermission(EnvironmentPermissionAccess.Read, "UserName").Demand();
StringBuilder lpBuffer = new StringBuilder(0x100);
int capacity = lpBuffer.Capacity;
if (Win32Native.GetUserName(lpBuffer, ref capacity))
{
return lpBuffer.ToString();
}
return string.Empty;
}
}
Although Steve's answer is correct and most elegant, the following illustrates what you have done incorrectly:
1) Defining a fixed length string
Dim lpBuff As String * 25
Dim lpBuff As String
lpBuff = New String(CChar(" "), 25)
2) The return variable should be of type Integer
Public Function ReturnUserName() As String
Dim iReturn As Integer
Dim userName As String
userName = New String(CChar(" "), 50)
iReturn = GetUserName(userName, 50)
Return userName.Substring(0, userName.IndexOf(Chr(0)))
End Function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.