LDAP Directory Entry in .Net - not working with OU=Users

后端 未结 3 1137
庸人自扰
庸人自扰 2020-12-10 07:54

I have the following code (C#):

(Tweaked from: http://www.eggheadcafe.com/conversation.aspx?messageid=31766061&threadid=31766050)

DirectorySearcher         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 08:02

    The first thing I would try as a test is to hardcode your desired path when you create a directory entry like so:

    DirectoryEntry de = new DirectoryEntry("LDAP://OU=Users,DC=company,DC=local");
    

    This will tell you pretty quick if this is an actual path in your Active Directory. I don't know what your AD looks like so I can't tell you if this is a valid path or not. Under your Active Directory Users and Computers MMC plugin, if this path is correct, then you should have your root domain, and a OU folder under the root called Users.

    Paths are generated backwards in AD, so if your Users folder is under another OU off the root than it would be

    DirectoryEntry de = new DirectoryEntry("LDAP://OU=Users,OU=,DC=company,DC=local");
    

    So your AD schema would look like:

     Root 
     |
     -->
         |
         -->Users
    

    A great article on how to manage Active Directory in .NET:

    HowTo: Do (Almost) Everything in Active Directory via C#

    You might also want to research the System.DirectoryServices, System.DirectoryServices.ActiveDirectory, and the System.DirectoryServices.AccountManagement namespaces provided in the .Net 3.5 Framework. I believe System.DirectoryServices, and ActiveDirctory namespaces were available staring in .Net 1.1, and AccountManagement was introduced in .Net 3.5.

    Microsoft Documentation - A lot of good links on how to use the namespace

    Addendum:

    To actually find a user in AD you will want to do the following:

     DirectoryEntry de = new DirectoryEntry();
     de.Path = "LDAP://DC=company,DC=local";
     de.AuthenticationType = AuthenticationTypes.Secure;
    
     DirectorySearcher deSearch = new DirectorySearcher();
    
     deSearch.SearchRoot = de;
     deSearch.Filter = "(&(objectClass=user) (cn=" + username + "))";
    
     SearchResult result = deSearch.FindOne();
    
     if (result != null)
     {
         DirectoryEntry deUser = new DirectoryEntry(result.Path);
         ... do what ever you need to the deUser
         deUser.Close();
     }
    

提交回复
热议问题