ALL Operations on Active Directory (AD) using c#

This article will explain how to perform operations on Active Directory (AD) using C#. In this step-by-step tutorial, I will build a class library (DLL) project that will perform all the AD Operations and then you can use this class library in any application to use this functionality.

Objective

This article will explain how to perform operations on Active Directory (AD) using C#.  In this step-by-step tutorial, I will build a class library (DLL) project that will perform all the AD Operations and then you can use this class library in any application to use this functionality.

Basic introduction of Active Directory is provided and code examples for operations like

  1. Finding user by login name
  2. Finding user by Name
  3. Finding user by First Name
  4. Resolving AD Group in users etc

What is Active Directory

This is a Directory structure used in Windows for storing information about networks and domains.  This was first used in Windows 2000.  This is a hierarchical structure which helps in organizing information on objects.  In lay term it is used to store user information, network information in an organization.

Solution Explorer for the Active Directory Helper Class library 

ADImg1.gif

ActiveDirectoryHelper is the main working class. This class will contain all the functions for various operations on AD. Other classes are helping class to perform operations and being used in ActiveDirectoryHelper class.  After adding DLL of this project, at the client side object of ActiveDirectory class will get created and the function will get called.

Diving into code to Perform Operations
 
Step 1

Create a new project by selecting project template Class Library.

Step 2

Add below references to the project

  • System.DirectoryServices
  • System.DirectoryServices.AccountManagement
  • System.DirectoryServices.Protocols.
  • System.Configuration

Step 3

Add an Application Configuration file to project.  And add App setting for

  1. LDAP User Name
  2. LDAP Password
  3. LDAP Path

So App.Config file will look like below,

App.Config
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.   <appSettings>  
  4.     <add key="LDAPPassword" value="xxxPasswordxxx " />  
  5.     <add key="LDAPPath" value="LDAP://domain/DC=xxx,DC=com" />  
  6.     <add key="LDAPUser" value="xxxUserxxx " />  
  7.   </appSettings>  
  8. </configuration>  
Note: Give user name, password and path according to your LDAP
 
Step 4. Creating ADUser class

Create or add a class in the project for ADUser details. This class will have the properties corresponding to the information of the AD User.

  1. This class has read only properties for fetching First Name, Last Name, City,Login Name etc.
  2. Constructor of the class is taking one parameterof type DirectoryEntry class.
  3. In Constructor all the information about ADUseris getting fetched using static class ADProperties.
  4. There are two static functions inside thisclass. GetUser and GetProperty
  5. GetProperty is returning a string which holds property of AD User.
  6. GetUser static function is returning anADUser.

ADUserDetail.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.DirectoryServices;  
  6. namespace ActiveDirectoryHelper  
  7. {  
  8.     public class ADUserDetail  
  9.     {  
  10.         private String _firstName;  
  11.         private String _middleName;  
  12.         private String _lastName;  
  13.         private String _loginName;  
  14.         private String _loginNameWithDomain;  
  15.         private String _streetAddress;  
  16.         private String _city;  
  17.         private String _state;  
  18.         private String _postalCode;  
  19.         private String _country;  
  20.         private String _homePhone;  
  21.         private String _extension;  
  22.         private String _mobile;  
  23.         private String _fax;  
  24.         private String _emailAddress;  
  25.         private String _title;  
  26.         private String _company;  
  27.         private String _manager;  
  28.         private String _managerName;  
  29.         private String _department;  
  30.         public String Department  
  31.         {  
  32.             get { return _department; }  
  33.         }  
  34.         public String FirstName  
  35.         {  
  36.             get { return _firstName; }  
  37.         }  
  38.         public String MiddleName  
  39.         {  
  40.             get { return _middleName; }  
  41.         }  
  42.         public String LastName  
  43.         {  
  44.             get { return _lastName; }  
  45.         }  
  46.         public String LoginName  
  47.         {  
  48.             get { return _loginName; }  
  49.         }  
  50.         public String LoginNameWithDomain  
  51.         {  
  52.             get { return _loginNameWithDomain; }  
  53.         }  
  54.         public String StreetAddress  
  55.         {  
  56.             get { return _streetAddress; }  
  57.         }  
  58.         public String City  
  59.         {  
  60.             get { return _city; }  
  61.         }  
  62.         public String State  
  63.         {  
  64.             get { return _state; }  
  65.         }  
  66.         public String PostalCode  
  67.         {  
  68.             get { return _postalCode; }  
  69.         }  
  70.         public String Country  
  71.         {  
  72.             get { return _country; }  
  73.         }  
  74.         public String HomePhone  
  75.         {  
  76.             get { return _homePhone; }  
  77.         }  
  78.         public String Extension  
  79.         {  
  80.             get { return _extension; }  
  81.         }  
  82.         public String Mobile  
  83.         {  
  84.             get { return _mobile; }  
  85.         }  
  86.         public String Fax  
  87.         {  
  88.             get { return _fax; }  
  89.         }  
  90.         public String EmailAddress  
  91.         {  
  92.             get { return _emailAddress; }  
  93.         }  
  94.         public String Title  
  95.         {  
  96.             get { return _title; }  
  97.         }  
  98.         public String Company  
  99.         {  
  100.             get { return _company; }  
  101.         }  
  102.         public ADUserDetail Manager  
  103.         {  
  104.             get  
  105.             {  
  106.                 if (!String.IsNullOrEmpty(_managerName))  
  107.                 {  
  108.                     ActiveDirectoryHelper ad = new ActiveDirectoryHelper();  
  109.                     return ad.GetUserByFullName(_managerName);  
  110.                 }  
  111.                 return null;  
  112.             }  
  113.         }  
  114.         public String ManagerName  
  115.         {  
  116.             get { return _managerName; }  
  117.         }  
  118.         private ADUserDetail(DirectoryEntry directoryUser)  
  119.         {  
  120.             String domainAddress;  
  121.             String domainName;  
  122.             _firstName = GetProperty(directoryUser, ADProperties.FIRSTNAME);  
  123.             _middleName = GetProperty(directoryUser, ADProperties.MIDDLENAME);  
  124.             _lastName = GetProperty(directoryUser, ADProperties.LASTNAME);  
  125.             _loginName = GetProperty(directoryUser, ADProperties.LOGINNAME);  
  126.             String userPrincipalName = GetProperty(directoryUser, ADProperties.USERPRINCIPALNAME);  
  127.             if (!string.IsNullOrEmpty(userPrincipalName))  
  128.             {  
  129.                  domainAddress = userPrincipalName.Split('@')[1];  
  130.             }  
  131.             else  
  132.             {  
  133.                 domainAddress = String.Empty;  
  134.             }  
  135.             if (!string.IsNullOrEmpty(domainAddress))  
  136.             {  
  137.                 domainName = domainAddress.Split('.').First();  
  138.             }  
  139.             else  
  140.             {  
  141.                 domainName = String.Empty;  
  142.             }  
  143.             _loginNameWithDomain = String.Format(@"{0}\{1}", domainName, _loginName);  
  144.             _streetAddress = GetProperty(directoryUser, ADProperties.STREETADDRESS);  
  145.             _city = GetProperty(directoryUser, ADProperties.CITY);  
  146.             _state = GetProperty(directoryUser, ADProperties.STATE);  
  147.             _postalCode = GetProperty(directoryUser, ADProperties.POSTALCODE);  
  148.             _country = GetProperty(directoryUser, ADProperties.COUNTRY);  
  149.             _company = GetProperty(directoryUser, ADProperties.COMPANY);  
  150.             _department = GetProperty(directoryUser, ADProperties.DEPARTMENT);  
  151.             _homePhone = GetProperty(directoryUser, ADProperties.HOMEPHONE);  
  152.             _extension = GetProperty(directoryUser, ADProperties.EXTENSION);  
  153.             _mobile = GetProperty(directoryUser, ADProperties.MOBILE);  
  154.             _fax = GetProperty(directoryUser, ADProperties.FAX);  
  155.             _emailAddress = GetProperty(directoryUser, ADProperties.EMAILADDRESS);  
  156.             _title = GetProperty(directoryUser, ADProperties.TITLE);  
  157.             _manager = GetProperty(directoryUser, ADProperties.MANAGER);  
  158.             if (!String.IsNullOrEmpty(_manager))  
  159.             {  
  160.                 String[] managerArray = _manager.Split(',');  
  161.                 _managerName = managerArray[0].Replace("CN=""");  
  162.             }  
  163.         }  
  164.         private static String GetProperty(DirectoryEntry userDetail, String propertyName)  
  165.         {  
  166.             if (userDetail.Properties.Contains(propertyName))  
  167.             {  
  168.                 return userDetail.Properties[propertyName][0].ToString();  
  169.             }  
  170.             else  
  171.             {  
  172.                 return string.Empty;  
  173.             }  
  174.         }  
  175.         public static ADUserDetail GetUser(DirectoryEntry directoryUser)  
  176.         {  
  177.             return new ADUserDetail(directoryUser);  
  178.         }  
  179.     }  
  180. } 
Step 5: Creating ADProperties class

Create or add a class in the project for ADProperties. This class will have the properties corresponding to the information of the AD User.  This is a static class. This class is having all the properties as constant string for ADUser.  This class is giving readable name to all the properties of user details.

ADProperties.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace ActiveDirectoryHelper  
  6. {  
  7.     public static class ADProperties  
  8.     {  
  9.         public const String OBJECTCLASS = "objectClass";  
  10.         public const String CONTAINERNAME = "cn";  
  11.         public const String LASTNAME = "sn";  
  12.         public const String COUNTRYNOTATION = "c";  
  13.         public const String CITY = "l";  
  14.         public const String STATE = "st";  
  15.         public const String TITLE = "title";  
  16.         public const String POSTALCODE = "postalCode";  
  17.         public const String PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName";  
  18.         public const String FIRSTNAME = "givenName";  
  19.         public const String MIDDLENAME = "initials";  
  20.         public const String DISTINGUISHEDNAME = "distinguishedName";  
  21.         public const String INSTANCETYPE = "instanceType";  
  22.         public const String WHENCREATED = "whenCreated";  
  23.         public const String WHENCHANGED = "whenChanged";  
  24.         public const String DISPLAYNAME = "displayName";  
  25.         public const String USNCREATED = "uSNCreated";  
  26.         public const String MEMBEROF = "memberOf";  
  27.         public const String USNCHANGED = "uSNChanged";  
  28.         public const String COUNTRY = "co";  
  29.         public const String DEPARTMENT = "department";  
  30.         public const String COMPANY = "company";  
  31.         public const String PROXYADDRESSES = "proxyAddresses";  
  32.         public const String STREETADDRESS = "streetAddress";  
  33.         public const String DIRECTREPORTS = "directReports";  
  34.         public const String NAME = "name";  
  35.         public const String OBJECTGUID = "objectGUID";  
  36.         public const String USERACCOUNTCONTROL = "userAccountControl";  
  37.         public const String BADPWDCOUNT = "badPwdCount";  
  38.         public const String CODEPAGE = "codePage";  
  39.         public const String COUNTRYCODE = "countryCode";  
  40.         public const String BADPASSWORDTIME = "badPasswordTime";  
  41.         public const String LASTLOGOFF = "lastLogoff";  
  42.         public const String LASTLOGON = "lastLogon";  
  43.         public const String PWDLASTSET = "pwdLastSet";  
  44.         public const String PRIMARYGROUPID = "primaryGroupID";  
  45.         public const String OBJECTSID = "objectSid";  
  46.         public const String ADMINCOUNT = "adminCount";  
  47.         public const String ACCOUNTEXPIRES = "accountExpires";  
  48.         public const String LOGONCOUNT = "logonCount";  
  49.         public const String LOGINNAME = "sAMAccountName";  
  50.         public const String SAMACCOUNTTYPE = "sAMAccountType";  
  51.         public const String SHOWINADDRESSBOOK = "showInAddressBook";  
  52.         public const String LEGACYEXCHANGEDN = "legacyExchangeDN";  
  53.         public const String USERPRINCIPALNAME = "userPrincipalName";  
  54.         public const String EXTENSION = "ipPhone";  
  55.         public const String SERVICEPRINCIPALNAME = "servicePrincipalName";  
  56.         public const String OBJECTCATEGORY = "objectCategory";  
  57.         public const String DSCOREPROPAGATIONDATA = "dSCorePropagationData";  
  58.         public const String LASTLOGONTIMESTAMP = "lastLogonTimestamp";  
  59.         public const String EMAILADDRESS = "mail";  
  60.         public const String MANAGER = "manager";  
  61.         public const String MOBILE = "mobile";  
  62.         public const String PAGER = "pager";  
  63.         public const String FAX = "facsimileTelephoneNumber";  
  64.         public const String HOMEPHONE = "homePhone";  
  65.         public const String MSEXCHUSERACCOUNTCONTROL = "msExchUserAccountControl";  
  66.         public const String MDBUSEDEFAULTS = "mDBUseDefaults";  
  67.         public const String MSEXCHMAILBOXSECURITYDESCRIPTOR = "msExchMailboxSecurityDescriptor";  
  68.         public const String HOMEMDB = "homeMDB";  
  69.         public const String MSEXCHPOLICIESINCLUDED = "msExchPoliciesIncluded";  
  70.         public const String HOMEMTA = "homeMTA";  
  71.         public const String MSEXCHRECIPIENTTYPEDETAILS = "msExchRecipientTypeDetails";  
  72.         public const String MAILNICKNAME = "mailNickname";  
  73.         public const String MSEXCHHOMESERVERNAME = "msExchHomeServerName";  
  74.         public const String MSEXCHVERSION = "msExchVersion";  
  75.         public const String MSEXCHRECIPIENTDISPLAYTYPE = "msExchRecipientDisplayType";  
  76.         public const String MSEXCHMAILBOXGUID = "msExchMailboxGuid";  
  77.         public const String NTSECURITYDESCRIPTOR = "nTSecurityDescriptor";  
  78.     }  
  79. } 
Step 6. Creating ActiveDirectoryHelper class

  1. This class will have all the function to performoperations to Active Directory.
  2. There are fourproperties in the class

LDAPPath property

This property is reading the LDAPPath from config file.

  1. private  String LDAPPath  
  2. {  
  3.     get  
  4.     {  
  5.         return ConfigurationManager.AppSettings["LDAPPath"];  
  6.     }  
  7. }  
LDAPUser property

This property is reading the LDAP user from the config file.

  1. private  String LDAPUser  
  2. {  
  3.     get  
  4.     {  
  5.         return ConfigurationManager.AppSettings["LDAPUser"];  
  6.     }  
  7. } 

 

LDAPPassword property

This property is reading the LDAP Password from the config file.

  1. private String LDAPPassword  
  2. {  
  3.     get  
  4.     {  
  5.         return ConfigurationManager.AppSettings["LDAPPassword"];  
  6.     }  
  7. } 
Search Root Property

This Property is initializing the Directory entry by passing the LDAPUser, LDAPPAth, and LDAPPassword.  This property is creating a new instance DirectoryEntry and returning that.

  1. private DirectoryEntry SearchRoot  
  2. {  
  3.     get  
  4.     {  
  5.         if (_directoryEntry == null)  
  6.         {  
  7.             _directoryEntry = new DirectoryEntry(LDAPPath, LDAPUser, LDAPPassword, AuthenticationTypes.Secure);  
  8.         }  
  9.         return _directoryEntry;  
  10.     }  
  11. } 

Various operations in ActiveDirectoryHelper class 

Get User by Full Name

This function will take a full name as input parameter and return AD user corresponding to that.

  1. public ADUserDetail GetUserByFullName(String userName)  
  2. {  
  3.     try  
  4.     {  
  5.         _directoryEntry = null;  
  6.         DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);  
  7.         directorySearch.Filter = "(&(objectClass=user)(cn=" + userName + "))";  
  8.         SearchResult results = directorySearch.FindOne();  
  9.         if (results != null)  
  10.         {  
  11.             DirectoryEntry user = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);  
  12.             return ADUserDetail.GetUser(user);  
  13.         }  
  14.         else  
  15.         {  
  16.             return null;  
  17.         }  
  18.     }  
  19.     catch (Exception ex)  
  20.     {  
  21.         return null;  
  22.     }  
  23. } 
Get User by Login Name

This function will return AD user. This takes Login name as input parameter.

  1. public ADUserDetail GetUserByLoginName(String userName)  
  2. {  
  3.     try  
  4.     {  
  5.         _directoryEntry = null;  
  6.         DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);  
  7.         directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))";  
  8.         SearchResult results = directorySearch.FindOne();  
  9.         if (results != null)  
  10.         {  
  11.             DirectoryEntry user = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);  
  12.             return ADUserDetail.GetUser(user);  
  13.         }  
  14.         return null;  
  15.     }  
  16.     catch (Exception ex)  
  17.     {  
  18.         return null;  
  19.     }  
  20. } 
Get Users by from a AD Group by Group Name

This function will take a group name as input and return list of AD User in that group.

  1. public List<ADUserDetail> GetUserFromGroup(String groupName)  
  2. {  
  3.     List<ADUserDetail> userlist = new List<ADUserDetail>();  
  4.     try  
  5.     {  
  6.         _directoryEntry = null;  
  7.         DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);  
  8.         directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + groupName + "))";  
  9.         SearchResult results = directorySearch.FindOne();  
  10.         if (results != null)  
  11.         {  
  12.             DirectoryEntry deGroup = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);  
  13.             System.DirectoryServices.PropertyCollection pColl = deGroup.Properties;  
  14.             int count = pColl["member"].Count;  
  15.             for (int i = 0; i < count; i++)  
  16.             {  
  17.                 string respath = results.Path;  
  18.                 string[] pathnavigate = respath.Split("CN".ToCharArray());  
  19.                 respath = pathnavigate[0];  
  20.                 string objpath = pColl["member"][i].ToString();  
  21.                 string path = respath + objpath;  
  22.                 DirectoryEntry user = new DirectoryEntry(path, LDAPUser, LDAPPassword);  
  23.                 ADUserDetail userobj = ADUserDetail.GetUser(user);  
  24.                 userlist.Add(userobj);  
  25.                 user.Close();  
  26.             }  
  27.         }  
  28.         return userlist;  
  29.     }  
  30.     catch (Exception ex)  
  31.     {  
  32.         return userlist;  
  33.     }  
  34. } 
Get Users and Group by from a AD basis on starting with string

This function will return Users and Group information from AD on basis of first characters. Wild character * is used to filter the criteria. 

  1. public List<ADUserDetail> GetUsersByFirstName(string fName)  
  2. {  
  3.     //UserProfile user;  
  4.     List<ADUserDetail> userlist = new List<ADUserDetail>();  
  5.     string filter = "";  
  6.     _directoryEntry = null;  
  7.     DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);  
  8.     directorySearch.Asynchronous = true;  
  9.     directorySearch.CacheResults = true;  
  10.     //directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))";  
  11.     filter = string.Format("(givenName={0}*", fName);  
  12.     //filter = "(&(objectClass=user)(objectCategory=person)" + filter + ")";  
  13.     filter = "(&(objectClass=user)(objectCategory=person)(givenName=" + fName + "*))";  
  14.     directorySearch.Filter = filter;  
  15.     SearchResultCollection userCollection = directorySearch.FindAll();  
  16.     foreach (SearchResult users in userCollection)  
  17.     {  
  18.         DirectoryEntry userEntry = new DirectoryEntry(users.Path, LDAPUser, LDAPPassword);  
  19.         ADUserDetail userInfo = ADUserDetail.GetUser(userEntry);  
  20.         userlist.Add(userInfo);  
  21.     }  
  22.     directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + fName + "*))";  
  23.     SearchResultCollection results = directorySearch.FindAll();  
  24.     if (results != null)  
  25.     {  
  26.         foreach (SearchResult r in results)  
  27.         {  
  28.             DirectoryEntry deGroup = new DirectoryEntry(r.Path, LDAPUser, LDAPPassword);  
  29.             // ADUserDetail dhan = new ADUserDetail();  
  30.             ADUserDetail agroup = ADUserDetail.GetUser(deGroup);  
  31.             userlist.Add(agroup);  
  32.         }  
  33.     }  
  34.     return userlist;  
  35. } 
Adding User to Active Directory Group

This function will take a user login name and add this to a group of AD.

  1. public bool AddUserToGroup(string userlogin, string groupName)  
  2. {  
  3.     try  
  4.     {  
  5.         _directoryEntry = null;  
  6.         ADManager admanager = new ADManager(LDAPDomain, LDAPUser, LDAPPassword);  
  7.         admanager.AddUserToGroup(userlogin, groupName);  
  8.         return true;  
  9.     }  
  10.     catch (Exception ex)  
  11.     {  
  12.         return false;  
  13.     }  
  14. } 
Removing User to Active Directory Group

This function will take a user login name and remove this to a group of AD.

  1. public bool RemoveUserToGroup(string userlogin, string groupName)  
  2. {  
  3.     try  
  4.     {  
  5.         _directoryEntry = null;  
  6.         ADManager admanager = new ADManager("xxx", LDAPUser, LDAPPassword);  
  7.         admanager.RemoveUserFromGroup(userlogin, groupName);  
  8.         return true;  
  9.     }  
  10.     catch (Exception ex)  
  11.     {  
  12.         return false;  
  13.     }  
  14. }

In above two functions ADManager class is being used for adding and removing user in AD.

ADManager.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.DirectoryServices.AccountManagement;  
  6. namespace ActiveDirectoryHelper  
  7. {  
  8.     public class ADManager  
  9.     {  
  10.         PrincipalContext context;  
  11.         public ADManager()  
  12.         {  
  13.             context = new PrincipalContext(ContextType.Machine, "xxx""xxx""xxx");  
  14.         }  
  15.         public ADManager(string domain, string container)  
  16.         {  
  17.             context = new PrincipalContext(ContextType.Domain, domain, container);  
  18.         }  
  19.         public ADManager(string domain, string username, string password)  
  20.         {  
  21.             context = new PrincipalContext(ContextType.Domain, username, password);  
  22.         }  
  23.         public bool AddUserToGroup(string userName, string groupName)  
  24.         {  
  25.             bool done = false;  
  26.             GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);  
  27.             if (group == null)  
  28.             {  
  29.                 group = new GroupPrincipal(context, groupName);  
  30.             }  
  31.             UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);  
  32.             if (user != null & group != null)  
  33.             {  
  34.                 group.Members.Add(user);  
  35.                 group.Save();  
  36.                 done = (user.IsMemberOf(group));  
  37.             }  
  38.             return done;  
  39.         }  
  40.         public bool RemoveUserFromGroup(string userName, string groupName)  
  41.         {  
  42.             bool done = false;  
  43.             UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);  
  44.             GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);  
  45.             if (user != null & group != null)  
  46.             {  
  47.                 group.Members.Remove(user);  
  48.                 group.Save();  
  49.                 done = !(user.IsMemberOf(group));  
  50.             }  
  51.             return done;  
  52.         }  
  53.     }  
  54. } 

This is the way all the operation could be perform on the AD.

Complete code for ActiveDirectoryHelper.cs class
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.DirectoryServices.AccountManagement;  
  6. namespace ActiveDirectoryHelper  
  7. {  
  8.     public class ADManager  
  9.     {  
  10.         PrincipalContext context;  
  11.         public ADManager()  
  12.         {  
  13.             context = new PrincipalContext(ContextType.Machine, "xxx""xxx""xxx");  
  14.         }  
  15.         public ADManager(string domain, string container)  
  16.         {  
  17.             context = new PrincipalContext(ContextType.Domain, domain, container);  
  18.         }  
  19.         public ADManager(string domain, string username, string password)  
  20.         {  
  21.             context = new PrincipalContext(ContextType.Domain, username, password);  
  22.         }  
  23.         public bool AddUserToGroup(string userName, string groupName)  
  24.         {  
  25.             bool done = false;  
  26.             GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);  
  27.             if (group == null)  
  28.             {  
  29.                 group = new GroupPrincipal(context, groupName);  
  30.             }  
  31.             UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);  
  32.             if (user != null & group != null)  
  33.             {  
  34.                 group.Members.Add(user);  
  35.                 group.Save();  
  36.                 done = (user.IsMemberOf(group));  
  37.             }  
  38.             return done;  
  39.         }  
  40.         public bool RemoveUserFromGroup(string userName, string groupName)  
  41.         {  
  42.             bool done = false;  
  43.             UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);  
  44.             GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);  
  45.             if (user != null & group != null)  
  46.             {  
  47.                 group.Members.Remove(user);  
  48.                 group.Save();  
  49.                 done = !(user.IsMemberOf(group));  
  50.             }  
  51.             return done;  
  52.         }  
  53.     }  
  54.  
How to use this class library

Just add DLL or reference of this project to your application and make an Instance of ActiveDirectoryHelper class.  After an instance is created, you may call the functions and properties to perform the operations on AD.

Conclusion

This article explained all operations on Active Directory using c#. Thanks for reading.