I'm trying to find if a user has an Active Directory account by searching with their email address and checking the Enabled property (if I return Enabled as true - run code, if I return false - run other code, and if the results are null - return false because that email doesn't exist anymore). When I get to the foreach loop, it has found the user based on their email in result, but checking with the if and elses returns user as NULL.
public static bool DoesUserExist(string email, string domain)
{
var found = false;
using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain))
{
UserPrincipal user = new UserPrincipal(domainContext);
user.EmailAddress = email;
PrincipalSearcher search = new PrincipalSearcher(user);
search.QueryFilter = user;
PrincipalSearchResult<Principal> results = search.FindAll();
foreach (Principal result in results)
{
if (user.Enabled == true)
{
found = false;
Helpers.LogMessage("Active Directory Account is Enabled in " + domain + " domain");
}
else if (user.Enabled == false)
{
found = true;
Helpers.LogMessage("Active Directory User Account is Disabled in " + domain + " domain");
}
else if (user.Enabled == null)
{
found = true;
Helpers.LogMessage("No Active Directory Account Found in " + domain + " domain");
}
}
return found;
}
}
What am I missing to be able to access if the user is Enabled or Disabled in the foreach?