Updating Active Directory Field Using C#

In some cases you need to update one or more fields using C#, to do this follow-up the below code.

  • Make sure your application build is .Net 3.5

  • You need to add the following assemblies in your application reference
    • System.DirectoryServices.dll [C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll]
    • System.DirectoryServices.AccountManagement.dll [C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.DirectoryServices.AccountManagement.dll]
  • You need the following namespaces
    • using System.DirectoryServices.AccountManagement;
    • using System.DirectoryServices;

Here is the code

        public static bool UpdateFields(string Property, string sUserName, string Value)
            bool result = false;
            PrincipalContext domain = new PrincipalContext(ContextType.Domain, "", "OU=Users,DC=dev,DC=loc", ContextOptions.SimpleBind);
                // Search for the user in the domain
                PrincipalSearcher searcher = new PrincipalSearcher();
                UserPrincipal findUser = new UserPrincipal(domain);
                findUser.SamAccountName = sUserName;
                searcher.QueryFilter = findUser;
                UserPrincipal foundUser = (UserPrincipal)searcher.FindOne();
                if (foundUser != null)
                    using (DirectoryEntry baseEntry = foundUser.GetUnderlyingObject() as DirectoryEntry)
                        using (DirectoryEntry entry = new DirectoryEntry(baseEntry.Path, baseEntry.Username, "P@ssw0rd"))
                            entry.Properties[Property].Value = Value;
                            result = true;
                    return false;
            return result;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s