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

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

开始了:

 List usernames = new List(); 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(result!= null)逻辑