0

I'm trying to check if a user exists in Active Directory before creating it. I'm using the following code:

private static DirectoryEntry FindActiveDirectoryUser(string userName, string domainName)
    {
        using (DirectoryEntry domain = new DirectoryEntry("LDAP://" + domainName))
        {
            using (DirectorySearcher searcher = new DirectorySearcher(domain))
            {
                searcher.ReferralChasing = ReferralChasingOption.All;
                searcher.Filter = "(sAMAAccountName=" + userName + ")";
                return searcher.FindOne().GetDirectoryEntry();
            }
        }
    }

I'm getting the error

A referral was returned from the server.

for the variables userName and domainName, I tried both FQDN and pre-2000 username (e.g. DOMAIN\User), as well as simple domain and user names.

Does anyone know how to resolve this?

user884248
  • 2,134
  • 3
  • 32
  • 57

1 Answers1

2

Try This one.It will work

     public GetUserByLoginName(String userName)
    {


        try
        {
            using (HostingEnvironment.Impersonate())
            {

                // This code runs as the application pool user



                _directoryEntry = null;
                string path = "LDAP://xxx.local/DC=xxx,DC=xxx"; //your LDAP Address


                DirectorySearcher directorySearch = new DirectorySearcher(path);
                directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))";
                SearchResult results = directorySearch.FindOne();


            }

        }

        catch (Exception ex)
        {
            return null;
        }
    }
Badhon Ashfaq
  • 851
  • 6
  • 9