Dan*_*gel 7 c# active-directory
我需要获取当前用户的显示名称,并找不到始终有效的解决方案.为了清楚起见,我不是在寻找用户名.我需要"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))
{
IntPtr bufPtr;
try
{
string domain = Regex.Replace(username.ToString(), @"(.+)\\.+", @"$1");
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);
DomainController dc = DomainController.FindOne(context);
if (0 == NetUserGetInfo(dc.IPAddress,
Regex.Replace(username.ToString(), @".+\\(.+)", "$1"),
10, out bufPtr))
{
var userInfo = (USER_INFO_10) Marshal.PtrToStructure(bufPtr, typeof (USER_INFO_10));
return Regex.Replace(userInfo.usri10_full_name, @"(\S+), (\S+)", "$2 $1");
}
}
finally
{
NetApiBufferFree(out bufPtr);
}
}
Run Code Online (Sandbox Code Playgroud)
通过上面的内容,我在调用DomainController.FindOne时收到一条消息"域中找不到域控制器"的ActiveDirectoryObjectNotFoundException.
我没有找到显示名称的注册表设置.
我不知道还有什么可以尝试的.请帮忙.
以上所有方法仅当您在域中时才有效。如果不是,则必须依赖本地用户帐户存储。以下详细介绍了如何检索此信息:如何获取本地 Windows 用户列表(仅显示在 Windows 登录屏幕中的用户)。但在域情况下,用户帐户将不在本地存储中。
如果您在域中但未连接到域控制器,则您将无法随时使用显示名称。此信息存储在域控制器上,而不是本地用户的计算机上。如果您的用户在域中,他们真的不应该禁用服务器服务(使用 GPO)。此外,他们失去的不仅仅是通过禁用该服务来检索其用户帐户的能力。
在尝试获取显示名称之前,我会检查域的可用性。如果失败,则显示一条指示失败的消息。这里可能有太多的边缘情况,无法解决所有这些问题。使用您打算使用该程序的场景,并为其他人提供错误消息。
| 归档时间: |
|
| 查看次数: |
2793 次 |
| 最近记录: |