Reputation: 999
I've used DirectoryEntry & DirectorySearcher for quite some time and it always works. Recently I learned about AccountManagement and thought I'd try it for a new project. But I can't get it to find me.
This old code work fine:
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
But I cannot make this work:
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();
}
}
Hoping someone can see what I'm doing wrong.
Upvotes: 1
Views: 798
Reputation: 40928
I think marc_s is on the right track. But you can just specify the domain the same way you do with DirectoryEntry
. You can use the constructor with only the domain name, like this:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "us.psy.com"))
That will search your whole domain.
That said, if you already know how to use DirectoryEntry
and DirectorySearcher
, you're better off sticking with it. The AccountManagement
namespace is just uses them in the background anyway. It can make some things easier, but it hides a lot from you, which hurts performance. Using DirectoryEntry
and DirectorySearcher
directly will almost always perform faster.
I talked a bit about that in an article I wrote (but also how to get better performance from DirectoryEntry
and DirectorySearcher
): Active Directory: Better Performance
Upvotes: 1