How can you find a user in active directory from C#?

后端 未结 8 655
时光取名叫无心
时光取名叫无心 2020-12-24 08:13

I\'m trying to figure out how to search AD from C# similarly to how \"Find Users, Contacts, and Groups\" works in the Active Directory Users and Computers tool. I have a str

相关标签:
8条回答
  • 2020-12-24 08:47

    You need to build the search string based on how you're looking for the user.

    using (var adFolderObject = new DirectoryEntry())
    {
         using(var adSearcherObject = new DirectorySearcher(adFolderObject))
         {
              adSearcherObject.SearchScope = SearchScope.Subtree;
              adSearcherObject.Filter = "(&(objectClass=person)(" + userType + "=" + userName + "))";
    
              return adSearcherObject.FindOne();
         }
    }
    

    userType should either be sAMAccountName or CN depending on how the username is formatted.

    ex:
    firstname.lastname (or flastname) will usually be the sAMAccountName
    FirstName LastName will usually be the CN

    0 讨论(0)
  • 2020-12-24 08:51

    System.DirectoryServices has two namespaces...DirectoryEntry and DirectorySearcher.

    More info on the DirectorySearcher here:

    http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx

    You can then use the Filter property to filter by Group, user etc...

    So if you wanted to filter by account name you would set the .Filter to:

    "(&(sAMAccountName=bsmith))"
    

    and run the FilterAll method. This will return a SearchResultCollection that you can loop through and pull information about the user.

    0 讨论(0)
提交回复
热议问题