• How to modify user in active directory using LDAP

    Posted on June 29, 2012 by in Dotnet Tips & Tricks, Tips & Tricks

    public static void ModifyUser(string username)
    {            
        //set active directory search base
        //DOMAIN PATH PATTERN: CN=Name,CN=Directory,DC=Domain,DC=com or simply server name
        DirectoryEntry directoryEntry = new DirectoryEntry(CONST_DOMAIN_PATH, CONST_AD_USERNAME, CONST_AD_PASSWORD);
    
        using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry))
        {                
            //Set a filters to get only specified user from AD
            directorySearcher.Filter = string.Format("({0})", "&(objectClass=user)(cn=" + username + ")");
    
            //Set Search Options
            directorySearcher.SearchScope = SearchScope.Subtree;
            directorySearcher.SearchRoot.AuthenticationType = AuthenticationTypes.Secure;
            directorySearcher.PageSize = 100;
    
            //run the search and returns only the first entry that is found.
            SearchResult result = directorySearcher.FindOne();
            if (result != null)
            {
                //     Retrieves the System.DirectoryServices.DirectoryEntry that corresponds to
                //     the System.DirectoryServices.SearchResult from the Active Directory Domain
                //     Services hierarchy.
                DirectoryEntry updateEntry = result.GetDirectoryEntry();
    
                //add or update the department property
                updateEntry.Properties["department"].Value = "100";
    
                //Saves changes that are made to a directory entry to the AD
                updateEntry.CommitChanges();
    
                //Close the System.DirectoryServices.DirectoryEntry object and releases any
                //system resources that are associated with this component.
                updateEntry.Close();
            }
            
            //release resources
            directorySearcher.Dispose();
            directoryEntry.Dispose();
        }
    }
    Be Sociable, Share!
      Post Tagged with

    Written by

    View all articles by

    Email : [email protected]qnownow.com

    Leave a Reply