CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Update a property Value in Active Directory in C#
Submitted By Satheesh Babu B
On 11/6/2008 6:47:44 AM
Tags: Active Directory,C#,CodeDigest  

Sometimes, we will have requirements to update a user property that is stored in Windows Active directory in C#.

 

The following code snippet will search for a user and update the mail property. Change the LDAP string to your infra's server name. I have narrowed down the search to search only users and with samaccountname property.

 

Include System.DirectoryServices namespace for the below code to work.

 

  DirectorySearcher sea = null;

                DirectoryEntry dir = null;

                DirectoryEntry d = null;

 

                try

                {

                    dir = new DirectoryEntry();                

                     dir.Path = "LDAP://MyADServer.com";

                    sea = new DirectorySearcher(dir);

                    sea.Filter = "(&(objectCategory=user)(samAccountName=" +txtUser.Text + "))";

                    SearchResult res = sea.FindOne();

                    d = new DirectoryEntry();

                    d.Path = res.Path;

                    d.Properties["mail"].Value = txtMail.Text;

                    d.CommitChanges();

             }

                catch (Exception ex)

                {

                    MessageBox.Show(ex.Message);

                }

                finally

                {

                    if (d != null)

                    {

                        d.Dispose();

                    }                 

                    if (sea != null)

                    {

                        sea.Dispose();

                    }

                    if (dir != null)

                    {

                        dir.Dispose();

                    }

                }

 

If we see the above, I have called FindOne() method with the filter condition which returns a single search result.

Remember to call CommitChanges() method which commits the change to AD. Missing this method will have no updation on Active Directory.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..