Search code examples
.netactive-directoryaccount-management

Searching Active Directory for a user with a certain property using DirectoryServices.AccountManagement


I'm new to accessing Active Directory and I was advised to use the System.DirectoryServices.AccountManagement namespace but I don't know how to search in it for a user with a certain initials.

Any help ?


Solution

  • Here is a full sample using PrincipalSearcher, even with your own attributes if you want (the code is as is).

    /* Looking for users
     */
    PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "root.123");
    
    /* Create a user principal to look for
     */
    slxUser aSlxUser = new slxUser(domainContext);
    aSlxUser.streetAddress = "The Adress"
    
    /* FindAll
     */
    PrincipalSearchResult<Principal> results = new PrincipalSearcher(aSlxUser).FindAll();
      Console.WriteLine(results.Count());
    

    With this definition for slxUser :

    [DirectoryObjectClass("user")]
    [DirectoryRdnPrefix("CN")]
    class slxUser : UserPrincipal
    {
      public slxUser(PrincipalContext context)
        : base(context) { }
    
      public slxUser(PrincipalContext context, string samAccountName, string password,  bool enabled ) : base(context, samAccountName, password, enabled)
      {
      }
    
      [DirectoryProperty("streetAddress")]
      public string streetAddress
      {
        get
        {
          object[] result = this.ExtensionGet("streetAddress");
          if (result != null)
          {
            return (string)result[0];
          }
          else
          {
            return null;
          }
        }
        set { this.ExtensionSet("streetAddress", value); }
      }
    }