问题
I am trying to search the AD on a new domain and new domain controller as our network has recently expanded. The domain I specify below is the domain the web server is joined to. I will refer to this as domainA and it works correctly. When I change it to domainB, it appears to always return results from domainA. I can put the new domain entry or even any string like "blahblahblah" inside DirectorySeracher() and it returns results from DomainA. Is it falling back to the domain the web server is joined to somehow if it can't find the domain I specify? I don't get any errors, just results from the wrong domain.
DirectorySearcher dssearch = new DirectorySearcher("LDAP://CN=users,DC=LAZARUS,DC=COM");
dssearch.Filter = "(&(objectClass=user)(sAMAccountName=" + txtusername.Text + "))";
SearchResult sresult = dssearch.FindOne();
if ( sresult != null ){
lblStatus.Visible = false;
DirectoryEntry dsresult = sresult.GetDirectoryEntry();
lblfname.Text = dsresult.Properties["givenName"][0].ToString();
lbllname.Text = dsresult.Properties["sn"][0].ToString();
lblTitle.Text = dsresult.Properties["description"][0].ToString();
lblHire.Text = dsresult.Properties["whencreated"][0].ToString();
pnlForm.Visible = false;
pnlResults.Visible = true;
btnReset.Visible = true;
}else{
lblStatus.Visible = true;
lblStatus.Text = "User not found.";
}
回答1:
The constructor you used DirectorySearcher(string)
is actually expecting the filter, but not the search root path.
DirectorySearcher dssearch = new DirectorySearcher("LDAP://CN=users,DC=LAZARUS,DC=COM");
And in the 2nd line you overwrite the value of the filter
dssearch.Filter = "(&(objectClass=user)(sAMAccountName=" + txtusername.Text + "))";
So anything you passed to the ctor has no effect at all.
Search root for DirectorySearcher
must be passed as DirectoryEntry
.
You may pick the most appropriate ctor in the following link.
http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher%28v=vs.110%29.aspx
来源:https://stackoverflow.com/questions/25653667/check-if-the-directoryentry-is-valid-in-directorysearcher