【发布时间】:2010-06-07 14:27:35
【问题描述】:
我尝试获取当前登录用户的全名(全名,而不是用户名)。
以下代码 C#、C++ 工作正常,但在未连接到网络的 XP 计算机上,如果我在登录后约 20 分钟运行它会得到空字符串(它在第一个 ~20 分钟后运行正常登录)
使用 Win32 API (GetUserNameEx) 而不是 PrincipalContext,因为 PrincipalContext 在离线工作时可能需要长达 15 秒。
任何帮助,为什么我得到一个空字符串作为结果虽然指定了用户全名???
- C#代码
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);
- 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;
}
【问题讨论】: