We then use some logic to determine if the user is locked out
if they are, we try to create a User object based on their distinguishedName, and the code fails at this point:
public UserAccount(string distinguishedName)
{
_dn = distinguishedName;
//It seems .Exists does not function correctly, and returns a COMException instead of false.
try {
if (DirectoryEntry.Exists("LDAP://" + _dn))
//do something
} catch (Exception ce) {
throw new ActiveDirectoryObjectNotFoundException("User account not found: " + distinguishedName, typeof(DirectoryEntry), distinguishedName);
}
//more stuff here
}
The .exists method returns false (or rather an exception, which i catch) for any users whose OU=Disabled/Inactive Users
(i.e. distinguishedName = "CN=Lastname\, Firstname,OU=Disabled/Inactive Users,DC=oursite,DC=com")
Basically, I want to know why sAMAccountName=* returns a user, but .exists cannot find that user (is this expected behaviour for disabled users, or am i doing something wrong?)
irfanj
Member
10 Points
8 Posts
DirectoryEntry.Exists not working as expected
Nov 23, 2011 07:36 PM|LINK
First of all, I have read that DirectoryEntry.exists does not function correctly (http://connect.microsoft.com/VisualStudio/feedback/details/337682/directoryentry-exists-throws-exception-for-non-existent-winnt-object)
I just want to confirm that this is true, because my next question is based on that
The workaround (for us) was to enclose it in a try/catch block with the "false" code in the catch.
We use a bit of code to find all users that are locked out, and I am getting an error I don't understand
Basically, the code runs and generates the equivalent of this:
DirectorySearcher(searchRoot, ldapFilter, attributes); //DirectoryEntry searchRoot = new DirectoryEntry(); //ldapFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=*)) //string[] attributes = { "distinguishedName", "sAMAccountName", "msDS-User-Account-Control-Computed" };This returns all the users (as expected)
We then use some logic to determine if the user is locked out
if they are, we try to create a User object based on their distinguishedName, and the code fails at this point:
public UserAccount(string distinguishedName) { _dn = distinguishedName; //It seems .Exists does not function correctly, and returns a COMException instead of false. try { if (DirectoryEntry.Exists("LDAP://" + _dn)) //do something } catch (Exception ce) { throw new ActiveDirectoryObjectNotFoundException("User account not found: " + distinguishedName, typeof(DirectoryEntry), distinguishedName); } //more stuff here }The .exists method returns false (or rather an exception, which i catch) for any users whose OU=Disabled/Inactive Users
(i.e. distinguishedName = "CN=Lastname\, Firstname,OU=Disabled/Inactive Users,DC=oursite,DC=com")
Basically, I want to know why sAMAccountName=* returns a user, but .exists cannot find that user (is this expected behaviour for disabled users, or am i doing something wrong?)