I'm trying to use the GetUserName API function in the advapi32.dll library.
I declare my function as follows:
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA"
(ByVal lpBuffer As String, ByVal nsize As Long) As Long
But when I call the function like this:
lngRetVal = GetUserName(strName, lngSize)
I get the following error:
'Object reference not set to an instance of an object.'
Does anyone know how I can fix this?
Thanks,
Parveen
As mentioned, you don't need this API call since this functionality is
implemented in the framework - System.Environment.UserName.
But, I am going to mention some problems with your above declare anyway
1. Long in VB.NET is 64-Bit. Integer is 32-Bit. So, you'll want to
replace your Longs with Integers.
2. Drop the Alias. It is much more effiecient to declare the function
as Auto and let the runtime call the appropriate function. This way,
when running on NT based systems you avoid a lot of unnecessary string
conversions.
3. Don't use String for writeable buffers. For buffers that are going
to be filled with by the API call you should use
System.Text.StringBuilder. While it will work in VB.NET to use string
(the marshaller is smart enough to deal with it), it is really for
backwards compatability. Using the String type will not work in C#.
This is because the String data type is meant to be a immutable buffer.
Further, because of the extra work on the part of the marshaller, performance
will suffer. Of course, performance may not be an issue in cases
where the function is only called one time - but it still violates the
intent of the string data type.
4. The reason your getting your error: the API call expects the nSize
parameter to be passed ByRef
So, given the above - your declare:
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA"
(ByVal lpBuffer As String, ByVal nsize As Long) As Long
Should really be:
Declare Auto Function GetUserName Lib "advapi32.dll" _
(ByVal lpBuffer As System.Text.StringBuilder, _
ByRef nSize As Integer) As Boolean
Then you would call it like this:
Dim buffer As New System.Text.StringBuilder(256)
Dim nSize As Integer = buffer.Capacity
If GetUserName(buffer, nSize) Then
Return buffer.ToString()
Else
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
HTH