从活动目录访问所有用户

时间:2015-05-15 09:49:13

标签: c# active-directory

我想要所有活动目录用户。我尝试了以下代码,但只有CN属性可用。不返回这些其他属性:

1)的用户名
2)电子邮件
3)phoneno

抛出ObjectReferance错误。

 using (var context = new PrincipalContext(ContextType.Domain, "mydomain.com"))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        string str = de.Properties["SN"].Value.ToString();
                    }
                }
            }

1 个答案:

答案 0 :(得分:0)

   public class Users
        {
             public string Email { get; set; }
public string UserName { get; set; }
public string DisplayName { get; set; }
public bool isMapped { get; set; }


        }



 try
{

    string DomainPath = "";
    DirectoryEntry searchRoot = new DirectoryEntry(DomainPath); 
    DirectorySearcher search = new DirectorySearcher(searchRoot);
    search.Filter = "(&(objectClass=user)(objectCategory=person))";
    search.PropertiesToLoad.Add("samaccountname");
    search.PropertiesToLoad.Add("mail");
    search.PropertiesToLoad.Add("usergroup");
    search.PropertiesToLoad.Add("displayname");

    SearchResult result;
    SearchResultCollection resultCol = search.FindAll();
    if (resultCol != null)
    {
        for (int counter = 0; counter < resultCol.Count; counter++)
        {
            string UserNameEmailString = string.Empty;
            result = resultCol[counter];
            if (result.Properties.Contains("samaccountname") && 
                     result.Properties.Contains("mail") && 
                result.Properties.Contains("displayname"))
            {
                Users objSurveyUsers = new Users();
                objSurveyUsers.Email = (String)result.Properties["mail"][0];
                objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];

                lstADUsers.Add(objSurveyUsers);
            }
        }
    }

}
catch (Exception ex)
{

}