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?

4

1 回答 1

2

试试这个。它会工作的

     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;
        }
    }
于 2014-05-16T12:49:30.250 回答