Heybo Blog

If you look at me when I'm talking, you'll see what I'm saying ... about Tech and .NET discoveries!

My Links

News

Story Categories

Archives

Post Categories

Image Galleries

Login

Blog Stats

Links

Personal Websites

Connecting to Active Directory with C# using DirectoryServices.dll

I have struggled for a while to figure this out and decided you may need some help too. Below is the code that  you need to get a name for a domain user name. You should be able to get other properties by adding the desired properties by using the PropertiesToLoad method. This uses LDAP and remember to import the System.DirectoryServices library/namespace.

try
{
  System.DirectoryServices.DirectoryEntry dse =
    new System.DirectoryServices.DirectoryEntry("LDAP://YourDomain");
   System.DirectoryServices.DirectorySearcher dSearch =
    new System.DirectoryServices.DirectorySearcher(dse);
   dSearch.Filter = "(&(objectClass=user)(cn=" + "yourname" + "))";
   dSearch.PropertiesToLoad.Add("displayname");
   System.DirectoryServices.SearchResultCollection sr = dSearch.FindAll();
   if ( !(sr == null ) )
   {
    foreach ( System.DirectoryServices.SearchResult srr in sr )
    {
     System.DirectoryServices.ResultPropertyCollection  r = srr.Properties;
     foreach ( System.DirectoryServices.ResultPropertyValueCollection
          o in r.Values )
     {
      Console.WriteLine(o[0].ToString());
     }
    }
   }
}
catch(Exception ex)
{
    MessageBox.Show("Error authenticating. " + ex.Message);
}

posted on Monday, October 11, 2004 11:37 AM

Feedback

No comments posted yet
Title  
Name  
Url
Comments   
Protected by Clearscreen.SharpHIPEnter the code you see: