搜索Active Directory,查找与电子邮件地址相关联的所有用户名。

3

我有一个基于电子邮件地址在Active Directory中搜索用户名的方法。有时会出现一个电子邮件地址对应多个用户名的情况,我正在尝试捕获这些情况。我已经重写了我的方法,但似乎语法不太正确。我认为问题出在这一行。

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

thanks,

Jason

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";
    }
}

GetDirectoryEntry() ? - Serj Sagan
1个回答

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();

只需用我的逻辑替换你的 if (result != null) 逻辑即可。

谢谢您的回复。现在它正在返回与电子邮件地址相关联的活动目录中的最后一个用户名。我只有6个用户,其中4个与该电子邮件相关联。 - Jason
当我运行调试并逐步查看结果时,我可以看到每个预期的用户名。但只有最后一个被写出来。 - Jason
这将在屏幕上输出所有用户:Response.Write(users + "<br />"); - Jason
@Jason,那是因为你正在将它写入列表框中,请将其更改为输出到某种列表中,我会相应地更新我的代码。 - TBohnen.jnr
再次感谢您的帮助。我遇到了一个错误,即“System.Collections.Generic.List<string>.Add(string)”的最佳重载方法匹配有一些无效参数。 - Jason
愉快,已修复,需要将对象强制转换为字符串类型。 - TBohnen.jnr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接