All about Active Directory Programming in C#

In this blog, we will see Active Directory Programming using C# code.
In other blogs, you can read ASP.Net Tutorial, .Net Core Tutorial.
We will first understand - What is Active Directory?


Active Directory

Active Directory is a central database for your organization. It keeps the record in various domain.
This is a Directory structure used in Windows operating system to store information related to networks and domains within an organization. Active Directory was first introduced in Windows 2000.  Active Directory is a hierarchical structure which helps an organization in organizing information.
We can create groups, users in Active Directory.
Active Directory console can be view using "DCPROMO" command in Run window.
Using programming we can access Active Directory.

To start working with Active Directory using C# programming you need to use System.DirectoryServices name space. See below 3 namespaces which have been used in C# code.

System.DirectoryServices;
System.DirectoryServices.ActiveDirectory;
System.DirectoryServices.AccountManagement;


Below is the code to access Active Directory.


using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;

namespace ActiveDirectoryProgram
{
    class Program
    {
        static void Main(string[] args)
        {
           string ldapPath = GetLdap("corp");
            Program objP = new Program();
            objP.Authenticate("administrator", "password", "corp");
            objP.CreateUserAccount(ldapPath, "user", "password");
            GetOUForUser(@"corp\username");
        }

Below code is to get OU group name


//Get OU group name

        public static string GetOUForUser(string samAccountName)
        {
            using (var context = new PrincipalContext(ContextType.Domain))
            {
                using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName))
                {
                    //System.Console.WriteLine(user.DistinguishedName);
                    int startIndex = user.DistinguishedName.IndexOf("OU=", 1) + 3; //+3 for  length of "OU="
                    int endIndex = user.DistinguishedName.IndexOf(",", startIndex);
                    var group = user.DistinguishedName.Substring((startIndex), (endIndex - startIndex));
                    return group;
                }
            }
        }


Below is the code to get LDAP Path


//Get LDAP Path

        public static string GetLdap(string friendlyDomainName)
        {
            string ldapPath = null;
            try
            {
                DirectoryContext objContext = new DirectoryContext(
                    DirectoryContextType.Domain, friendlyDomainName);
                Domain objDomain = Domain.GetDomain(objContext);
                ldapPath = objDomain.Name;
            }
            catch (DirectoryServicesCOMException e)
            {
                ldapPath = e.Message.ToString();
            }
            return ldapPath;
        }

Below C# code is to Authenticate AD user


//Authenticate user

        private bool Authenticate(string userName, string password, string domain)
        {
            bool authentic = false;
            try
            {
                DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain,
                    userName, password);
                object nativeObject = entry.NativeObject;
                authentic = true;
            }
            catch (DirectoryServicesCOMException) { }
            return authentic;
        }

C# code to create new user in Active Directory


//Create New User

        public string CreateUserAccount(string ldapPath, string userName, string userPassword)
        {
            string oGUID = string.Empty;
            try
            {
                
                string connectionPrefix = "LDAP://" + ldapPath;
                DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
                DirectoryEntry newUser = dirEntry.Children.Add
                    ("CN=" + userName, "user");
                newUser.Properties["samAccountName"].Value = userName;
                newUser.CommitChanges();
                oGUID = newUser.Guid.ToString();

                newUser.Invoke("SetPassword", new object[] { userPassword });
                newUser.CommitChanges();
                dirEntry.Close();
                newUser.Close();
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException E)
            {
                //DoSomethingwith --> E.Message.ToString();

            }
            return oGUID;
        }


C# code to enable user in Active Directory


//Enable User

        public void Enable(string userDn)
        {
            try
            {
                DirectoryEntry user = new DirectoryEntry(userDn);
                int val = (int)user.Properties["userAccountControl"].Value;
                user.Properties["userAccountControl"].Value = val & ~0x2;
                //ADS_UF_NORMAL_ACCOUNT;

                user.CommitChanges();
                user.Close();
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException E)
            {
                //DoSomethingWith --> E.Message.ToString();

            }
        }

C# code to disable user in Active Directory


//Disable User

        public void Disable(string userDn)
        {
            try
            {
                DirectoryEntry user = new DirectoryEntry(userDn);
                int val = (int)user.Properties["userAccountControl"].Value;
                user.Properties["userAccountControl"].Value = val | 0x2;
                //ADS_UF_ACCOUNTDISABLE;

                user.CommitChanges();
                user.Close();
            }
            catch (System.DirectoryServices.DirectoryServicesCOMException E)
            {
                //Log exception message;

            }
        }

C# code to reset password of a user in Active Directory


//Reset Password

        public void ResetPassword(string userDn, string password)
        {
            DirectoryEntry uEntry = new DirectoryEntry(userDn);
            uEntry.Invoke("SetPassword", new object[] { password });
            uEntry.Properties["LockOutTime"].Value = 0; //unlock account

            uEntry.Close();
        }


    }
}

Protected by Copyscape

Comments

  1. very good post on Active Directory programming. Post more on this topic. Thanks.

    ReplyDelete
  2. very Good topic

    ReplyDelete

Post a Comment

Dear Readers, Please post your valuable feedback in the comment section if you like this blog or if you have any suggestions. I would love to hear the same from you. Thanks

Popular