CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Update a property for multiple users in Active Directory using C#
Submitted By Satheesh Babu B
On 11/11/2008 7:14:52 AM
Tags: Active Directory,C#,CodeDigest  

Sometimes, we will have requirements to update a property for all the users in Windows Active directory in C#.

The following code snippet will help us doing it. Change the LDAP string to your infra's server name. I have narrowed down the search to search only users and with country as India for multiple updations.

 

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

           

 

SearchResultCollection seacoll = null;

                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)(co=India))";

                    seacoll = sea.FindAll();

 

                    d = new DirectoryEntry();

 

                    for (int i = 0; i < seacoll.Count; i++)

                    {

                        d.Path = seacoll[i].Path;                      

                        d.Properties["name"].Value = "value";

                        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 FindAll() method with the filter condition which returns search result collection. Iterate into the collection to find the property to update and update to new value.

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..