如何使用 C# 在 Active Directory 中搜索用户的姓氏和名字
How can I search for both the user's last name AND the first name in the Active Directory using C#
当我只想搜索用户的姓氏时,我的这段代码非常有效
public static string GetPhoneFromAD()
{
try
{
DirectoryEntry entryDomain = new DirectoryEntry("LDAP://" + domain);
DirectorySearcher ds = new DirectorySearcher(entryDomain);
string currentContextIdentity = System.Web.HttpContext.Current.User.Identity.Name;
string lastName = currentContextIdentity.Split(' ')[currentContextIdentity.Split(' ').Length - 1];
ds.Filter = "(sn=" + lastName + ")";
SearchResult sr = ds.FindOne();
string telephoneNumber = sr.Properties["telephoneNumber"][0].ToString();
return FormatPhone(telephoneNumber);
}
catch (Exception exception)
{
drmsda.InsertErrorlog("manage.aspx.cs", "Error in an attempt to get the phone number", exception.Source, exception.Message + " " + exception.StackTrace, "");
drmsda.sendErrorEmail("Error: SetPhone generated email", exception.Message);
return string.Empty;
}
}
但是,如果用户的姓氏很常见,例如 Smith,我将无法正确输入。因此,我想添加另一个条件,例如名字。但是,我提出的查询不起作用。我确实尝试了以下
ds.Filter = "(givenName=" + firstName + "&sn=" + lastName + ")";
但这不起作用,有人可以帮忙吗?
提前致谢
LDAP 过滤器语法与那个有点不同;你想要:
(&(givenName=joe)(sn=bloggs))
有关许多示例,请参阅 here。
当我只想搜索用户的姓氏时,我的这段代码非常有效
public static string GetPhoneFromAD()
{
try
{
DirectoryEntry entryDomain = new DirectoryEntry("LDAP://" + domain);
DirectorySearcher ds = new DirectorySearcher(entryDomain);
string currentContextIdentity = System.Web.HttpContext.Current.User.Identity.Name;
string lastName = currentContextIdentity.Split(' ')[currentContextIdentity.Split(' ').Length - 1];
ds.Filter = "(sn=" + lastName + ")";
SearchResult sr = ds.FindOne();
string telephoneNumber = sr.Properties["telephoneNumber"][0].ToString();
return FormatPhone(telephoneNumber);
}
catch (Exception exception)
{
drmsda.InsertErrorlog("manage.aspx.cs", "Error in an attempt to get the phone number", exception.Source, exception.Message + " " + exception.StackTrace, "");
drmsda.sendErrorEmail("Error: SetPhone generated email", exception.Message);
return string.Empty;
}
}
但是,如果用户的姓氏很常见,例如 Smith,我将无法正确输入。因此,我想添加另一个条件,例如名字。但是,我提出的查询不起作用。我确实尝试了以下
ds.Filter = "(givenName=" + firstName + "&sn=" + lastName + ")";
但这不起作用,有人可以帮忙吗?
提前致谢
LDAP 过滤器语法与那个有点不同;你想要:
(&(givenName=joe)(sn=bloggs))
有关许多示例,请参阅 here。