我需要获取当前用户的显示名称,并找不到始终有效的解决方案.为了清楚起见,我不是在寻找用户名.我需要"John Doe"."开始"菜单上显示的值.
关于这个问题有很多帖子,但没有一个解决了我的问题.
这两个帖子引导我:
PrincipalContext context = domain.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase) ?
new PrincipalContext(ContextType.Machine) :
new PrincipalContext(ContextType.Domain, domain);
UserPrincipal userPrincipal = new UserPrincipal(context) { SamAccountName = username };
PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal);
userPrincipal = searcher.FindOne() as UserPrincipal;
string displayName = userPrincipal.DisplayName;
Run Code Online (Sandbox Code Playgroud)
这段代码大部分都适用.但是,如果用户已在其计算机上禁用/停止了服务器服务,则会出现"服务器服务未启动"的异常.
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
Run Code Online (Sandbox Code Playgroud)
同样的错误.
StringBuilder name = new StringBuilder(1024);
uint userNameSize = (uint)name.Capacity;
const int NameDisplay = 3;
GetUserNameEx(NameDisplay, name, ref userNameSize)
Run Code Online (Sandbox Code Playgroud)
不返回错误,但如果用户不在域中,则返回空字符串.
如何可靠地在所有版本的Windows上读取用户的显示(第一个和最后一个)名称?
// get SAM compatible name <server/machine>\\<username>
if (0 != GetUserNameEx(2, username, ref userNameSize))
{ …
Run Code Online (Sandbox Code Playgroud) 如何使用Windows API或其他方式获取登录用户的全名(他/她输入的真实姓名)?例如,如何获取“ John Smith”,而不是“ john”(因为这是他的用户名)。
GetUserName(...)不会执行此操作,因为它返回用户名,而不是全名。