Active Directory in .NET

This little snippet from Ian Atkinson really helped me when I was trying to update a user’s Active Directory details from my work’s corporate intranet.

using System;
using System.Text;
using System.DirectoryServices;

namespace activeDirectoryLdapExamples
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.Write("Enter user      : ");
      String username = Console.ReadLine();

      try
      {
        DirectoryEntry myLdapConnection = createDirectoryEntry();

        DirectorySearcher search = new DirectorySearcher(myLdapConnection);
        search.Filter = "(cn=" + username + ")";
        search.PropertiesToLoad.Add("title");

        SearchResult result = search.FindOne();

        if (result != null)
        {
          // create new object from search result

          DirectoryEntry entryToUpdate = result.GetDirectoryEntry();

          // show existing title

          Console.WriteLine("Current title   : " + 
            entryToUpdate.Properties["title"][0].ToString());

          Console.Write("\n\nEnter new title : ");

          // get new title and write to AD

          String newTitle = Console.ReadLine();

          entryToUpdate.Properties["title"].Value = newTitle;
          entryToUpdate.CommitChanges();

          Console.WriteLine("\n\n...new title saved");
        }

        else Console.WriteLine("User not found!");
      }

      catch (Exception e)
      {
        Console.WriteLine("Exception caught:\n\n" + e.ToString());
      }
    }

    static DirectoryEntry createDirectoryEntry()
    {
      // create and return new LDAP connection with desired settings

      DirectoryEntry ldapConnection     = new DirectoryEntry("rizzo.leeds-art.ac.uk");
      ldapConnection.Path               = "LDAP://OU=staffusers,DC=leeds-art,DC=ac,DC=uk";
      ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
      return ldapConnection;
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *