Saturday, April 25, 2009

How to get sAMAccountName from Active Directory

using System.DirectoryServices;

private string GetsAMAccountName()

    string domuser = PContext.Current.Web.CurrentUser.LoginName.Trim();
    domuser = domuser.Substring(domuser.IndexOf(@"\")+ 1);
    string ret = "";

    //init ldap call
    DirectoryEntry dentry = new DirectoryEntry("LDAP://server");

    //search ldap
    DirectorySearcher dsearcher = new DirectorySearcher(dentry);
    dsearcher.PageSize = 1000;
    dsearcher.Filter = ("(&(|(objectClass=person)(objectClass=user))(sAMAccountName=" + domuser + "))");

     // find users
     foreach (System.DirectoryServices.SearchResult sres in dsearcher.FindAll())
     {        
        DirectoryEntry de = sres.GetDirectoryEntry();         
        if(de.Properties["employeeID"]  != null && de.Properties["employeeID"].Value != null
         {
            string employee =  de.Properties["employeeID"].Value.ToString().Trim();             
            System.DirectoryServices.PropertyCollection props = de.Properties;             
            ret += props["sAMAccountName"][0];
         
         }
      }
      return ret;
}

No comments:

Post a Comment