There is a requirement to perform CRUD operation on an Active Directory and we need to create it on C#. The following code will help an engineer accordingly:
Create
using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP:\\url\ou", "username", "password"))
{
using (DirectoryEntry newUser = directoryEntry.Children.Add("CN=Name", "User"))
{
if (!DirectoryEntry.Exists(newUser.Path))
{
newUser.Properties["property1"].Add(propertyValue);
newUser.CommitChanges();
ret = true;
}
}
}
Update
using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP:\\url\ou", "username", "password"))
{
using (DirectorySearcher search = new DirectorySearcher(directoryEntry))
{
search.Filter = String.Format("(IdentifierProperty={0})", identifier);
search.PropertiesToLoad.Add("property1");
SearchResult result = search.FindOne();
if (result != null)
{
using (DirectoryEntry entryToUpdate = result.GetDirectoryEntry())
{
entryToUpdate.Properties["property1"].Value = "property1value";
entryToUpdate.CommitChanges();
ret = true;
}
}
}
}
Delete
using (DirectoryEntry directoryEntry = new DirectoryEntry("LDAP:\\url\ou", "username", "password"))
{
using (DirectorySearcher search = new DirectorySearcher(directoryEntry))
{
search.Filter = String.Format("(IdentifierProperty={0})", identifier);
search.PropertiesToLoad.Add("property1");
SearchResult result = search.FindOne();
if (result != null)
{
using (DirectoryEntry entryToUpdate = result.GetDirectoryEntry())
{
directoryEntry.Children.Remove(entryToUpdate);
directoryEntry.CommitChanges();
ret = true;
}
}
}
}


