Search code examples
c#active-directoryuserprincipalprincipalsearcher

Find if Active Directory is Enabled/Disabled with Email


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?


Solution

  • Your problem is user has nothing to do with the results of your search or the loop; it is just the template for searching. Also note that if no result is found, you will not enter the loop (results will be empty) and so testing for null makes no sense. Also, your found settings seem to be wrong.

    if (!results.Any())
        Helpers.LogMessage("No Active Directory Account Found in " + domain + " domain");
    else {
        var found = false;
    
        foreach (UserPrincipal result in results) {
            found = !result.Enabled;
            if (found)
                Helpers.LogMessage("Active Directory User Account is Disabled in " + domain + " domain");   
            else
                Helpers.LogMessage("Active Directory Account is Enabled in " + domain + " domain");
        }
    }