在Active Directory中搜索与电子邮件地址关联的所有用户名

时间:2011-04-14 15:11:59

标签: c# active-directory

我有一种方法可以根据电子邮件地址在Active Directory中搜索用户名。有些情况下,给定的电子邮件地址可能有多个用户名,我正在尝试捕获这些用户名。我已经重写了我的方法,但似乎无法使语法完全正确。我相信问题就在于这条线。

foreach (Object myObject in result.Properties[property])

感谢,

杰森

private String FindNameByEmail(string emailAddress)
{
    DirectoryEntry entry = GetDirectoryEntry();
    emailAddress = txtEmailID.Text;

    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(&(objectCategory=person)(sAMAccountName=*)(mail=" + emailAddress + "))";

    string[] properties = new string[] { "SAMAccountName" };
    foreach (String property in properties)
        search.PropertiesToLoad.Add(property);
    SearchResultCollection result = search.FindAll();

    if (result != null)
    {
        foreach (String property in properties)
           foreach (Object myObject in result.Properties[property])
                lblUserName.Text = myObject.ToString();
        return "User Found";
    }
    else
    {
        lblStatus.Text = "user does not exist";
        return "User Does Not Exist";
    }
}

1 个答案:

答案 0 :(得分:4)

编辑:将其更改为输出到字符串列表

我们走了:

List<string> usernames = new List<string>();
if (result != null) 
{
     foreach (SearchResult sr in result)
     {
         usernames.Add((string)sr.Properties["SAMAccountName"][0]);
     }
}
listBox1.DataSource = usernames; //Where listbox is declared in your markup
listBox1.DataBind();

用myne

替换你的if(结果!= null)逻辑