Set/Update Active Directory attributes to user
How to set/update Active Directory attributes to user.
Introduction
I was looking for code to easily update the accounts information in Active Directory. I got inspired from a very good article "Howto: (Almost) Everything In Active Directory via C#" which adds everything except this little part I am adding now. I am getting information from a MS-SQL database and run one account after the other to update the info.
This is just an extract of the code...
Using the code
A call to this class might look like:
myObjectReference.SetAdInfo("sAMAccountName" , Property.Title, "Vice President", "company.org")
The same calls can be done by setting the property to one of the items enumerated in the "public enum Property
" object in this class:
//
//Example of call: ADWork ADStuff = new ADWork();
// ADStuff.SetAdInfo(newemployeeID, ADWork.Property.title, newtitle, "CompanyDomain.org");
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;
using System.Data;
using System.Configuration;
class ADWork
{
public void SetAdInfo(string objectFilter, Property objectName,
string objectValue, string LdapDomain)
{
string connectionPrefix = "LDAP://" + LdapDomain;
DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(cn=" + objectFilter + ")";
mySearcher.PropertiesToLoad.Add(""+objectName+"");
SearchResult result = mySearcher.FindOne();
if (result != null)
{
DirectoryEntry entryToUpdate = result.GetDirectoryEntry();
if (!(String.IsNullOrEmpty(objectValue)))
{
if (result.Properties.Contains("" + objectName + ""))
{
entryToUpdate.Properties["" + objectName + ""].Value = objectValue;
}
else
{
entryToUpdate.Properties["" + objectName + ""].Add(objectValue);
}
entryToUpdate.CommitChanges();
}
}
entry.Close();
entry.Dispose();
mySearcher.Dispose();
}
public enum Property
{
title,displayName,sn,l,postalCode,physicalDeliveryOfficeName,telephoneNumber,
mail,givenName,initials,co,department,company,
streetAddress,employeeID,mobile,userPrincipalName
}
}
...
Hope it will be useful to everyone...