从Active Directory返回用户ID列表

时间:2015-10-15 14:35:00

标签: c# asp.net .net active-directory

创建一个名为GetAdUsers的方法,该方法应返回有关Active Directory中每个用户的一组信息(包括用户ID)。

我已成功归还用户EmailUserNameDisplayName,但无法获得用户的ID

  

如何从Active Directory获取用户ID。

我的用户模型

public class Users
{
    public string Email { get; set; }
    public string UserName { get; set; }
    public string DisplayName { get; set; }
    public bool IsMapped { get; set; }
    public int UserId { get; set; }
}

获取Active Directory信息的方法

public List<Users> GetAdUsers()
{
    try
    {
        List<Users> lstADUsers = new List<Users>();
        string DomainPath = ConfigurationManager.AppSettings["...ldapPathHere..."];

        // Encapsulating an object in Active Directory Domain Service - the DirectoryEntry is initializing a new instance of AD Domain Services
        DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);

        // Searching for all users in the domain
        DirectorySearcher search = new DirectorySearcher(searchRoot);

        // Filtering my results
        search.Filter = "(&(objectClass=user)(objectCategory=person))"; 
        search.PropertiesToLoad.Add("samaccountname");
        search.PropertiesToLoad.Add("mail");
        search.PropertiesToLoad.Add("usergroup");
        search.PropertiesToLoad.Add("displayname");//first name
        search.PropertiesToLoad.Add("userid");

        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") &&
                    result.Properties.Contains("userid"))
                {
                    Users objSurveyUsers = new Users();
                    objSurveyUsers.Email = (String)result.Properties["mail"][0] +
                      "^" + (String)result.Properties["displayname"][0];
                    objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                    objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                    objSurveyUsers.UserId = (int) result.Properties["userid"][0];
                    lstADUsers.Add(objSurveyUsers);
                }
            }
        }
        return lstADUsers;
    }
    catch (Exception ex)
    {
        throw;
    }
}

2 个答案:

答案 0 :(得分:0)

我认为您的意思是安全标识符或SID。这保存在where run_date >20151001 属性中。

答案 1 :(得分:0)

你的意思是samAccount或samAccountName吗?(我不确定哪一个是正确的)

编辑:

很抱歉,下次我应该完全阅读代码 - 不是LDAP查询区分大小写吗?