Getting the full-name of the current user, returns an empty string (C#/C++)
- by Nir
I try to get the full-name of the current log-in user (Fullname, not username).
The following code C#, C++ works fine but on XP computers not connected to the Net, I get empty string as result if I run it ~20 minutes after login (It runs OK whithin the first ~20 minutes after login)
A Win32 API (GetUserNameEx) is used rather that PrincipalContext since it PrincipalContext may takes up to 15 seconds when working offline.
Any Help why am I getting an empty string as result though a user full name is specified???
- C# Code
    public static string CurrentUserFullName
    {
        get
        {
            const int EXTENDED_NAME_FORMAT_NAME_DISPLAY = 3;
            StringBuilder userName = new StringBuilder(256);
            uint length = (uint) userName.Capacity;
            string ret;
            if (GetUserNameEx(EXTENDED_NAME_FORMAT_NAME_DISPLAY, userName, ref length))
            {
                ret = userName.ToString();
            }
            else
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception("GetUserNameEx Failed. Error code - " + errorCode);
            }
            return ret;
        }
    }
    [DllImport("Secur32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool GetUserNameEx(int nameFormat, StringBuilder lpNameBuffer, ref uint lpnSize);
- Code in C++
#include "stdafx.h"
#include <windows.h>
#define SECURITY_WIN32
#include <Security.h>
#pragma comment( lib, "Secur32.lib" )
int _tmain(int argc, _TCHAR* argv[])
{
    char szName[100];
    ULONG nChars = sizeof( szName );
    if ( GetUserNameEx( NameDisplay, szName, &nChars ) )
    {
        printf( "Name: %s\n", szName);
    }
    else
    {
        printf( "Failed to GetUserNameEx\n" );      
        printf( "%d\n", GetLastError() );
    }
    return 0;
}