In this blog, We will perform operations with Active Directory with C# Programming. Some of the operations such as enabling users, and disabling users.
Before moving ahead, We will first understand – What is an Active Directory.
What is Active Directory?
Active Directory is a central database for an organization. It keeps the record in various domains.
This is a Directory structure used in the Windows operating system to store information related to networks and domains within an organization. Active Directory was first introduced in Windows 2000.
We can create groups and users in Active Directory.
Active Directory console can be viewed using the “DCPROMO” command in the Run window. We can manage Active Directory operations from the console view. Alternatively, we can do the same using C# programming.
So, let’s start.
To start working with Active Directory using C# programming we need to use System.DirectoryServices
namespace. We will use the below 3 namespaces in C# code.
System.DirectoryServices;
System.DirectoryServices.ActiveDirectory;
System.DirectoryServices.AccountManagement;
Below is the code to get the LDAP Path
The very first task is to get the 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;
}
Here, we have a method GetLdap()
which returns the LDAP Directory path. In this method, we use DirectoryContext
class to get the context details.
C# Code to get OU group name
In an Active Directory, OU stands for Organizational Unit. These are nothing but containers where we can organize the company resources such as users and computers.
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;
}
}
}
Here, the method returns the OU group name based on the account name.
C# code to Authenticate AD user
We will now authenticate a user to LDAP using username, password and domain name.
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;
}
To authenticate a user, we use DirectoryEntry
class.
Create a new user in Active Directory with C# Code
We can also create a new user detail in LDAP using C# programming.
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 users in Active Directory
With C# code, we can enable a user’s account.
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();
}
}
Disable user in Active Directory with C# Code
We can also disable a user’s account using C# code.
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 the password of a user in Active Directory
We can use DirectoryEntry
class to reset a password for a user.
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();
}
Below is the code to access Active Directory
Finally, we write the C# code to authenticate and create a user in LDAP.
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(@"corpusername");
}
}
}
In the code snippet, we use the GetLdap()
method to fetch the LDAP path and then use Autehticate()
and CreateUserAccount()
method.
This article covers all the basic operations in Active Directory that we can do with C# code.
Hope you like this blog. Keep following: https://www.sharepointcafe.net/
Useful link: Active Directory Domain Services Overview | Microsoft Learn
very good post on Active Directory programming. Post more on this topic. Thanks.
very Good topic