繁体   English   中英

如何使用 DirectoryServices AccountManagement 查找用户?

[英]How do I find a user using DirectoryServices AccountManagement?

我已经使用 DirectoryEntry 和 DirectorySearcher 有一段时间了,它总是有效。 最近我了解了 AccountManagement 并想我会在一个新项目中尝试它。 但我不能让它找到我。

这段旧代码工作正常:

Using oDirectoryEntry As DirectoryEntry = New DirectoryEntry("LDAP://us.psy.com", "xxx2yyy", "MyStrongPwd")
    Using oDirectorySearcher As DirectorySearcher = New DirectorySearcher(oDirectoryEntry)
        oDirectorySearcher.Filter = "(&(sAMAccountType=805306368)(sAMAccountName=xxx2yyy))"
        Try
            Return oDirectorySearcher.FindOne IsNot Nothing
        Catch
            Return False
        End Try
    End Using
End Using

但我无法完成这项工作:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "US", "DC=psy,DC=com"))
{
    MessageBox.Show(context.ConnectedServer); // This shows me the server name
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "xxx2yyy"))
    {
        MessageBox.Show(user.SamAccountName); // results in Object reference not set to an instance of an object
        user.ChangePassword("OldPwd", "NewPwd");
        user.Save();
    }
}

希望有人能看到我做错了什么。

我认为 marc_s 走在正确的轨道上。 但是您可以像使用DirectoryEntry一样指定域。 您可以使用带有域名的构造函数,如下所示:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "us.psy.com"))

这将搜索您的整个域。

也就是说,如果您已经知道如何使用DirectoryEntryDirectorySearcher ,那么最好坚持使用它。 无论如何, AccountManagement命名空间只是在后台使用它们。 可以让一些事情变得更容易,但它对你隐藏了很多东西,这会影响性能。 直接使用DirectoryEntryDirectorySearcher几乎总是执行得更快。

我在我写的一篇文章中谈到了这一点(还有如何从DirectoryEntryDirectorySearcher获得更好的性能): Active Directory:更好的性能

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM