如何从活动目录中获取用户管理器电子邮件ID?我已经编写了代码,我可以根据用户ID获取用户的名字,姓氏,电子邮件ID和经理姓名,但我想获得经理电子邮件ID以及他的经理姓名。
有人可以帮我解决这个问题吗?这是我的代码:
protected void ddlAdsuser_SelectedIndexChanged(object sender, EventArgs e)
{
DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");
string myDomain = root.Properties["defaultNamingContext"].Value.ToString();
DirectoryEntry domain = new DirectoryEntry("LDAP://" + myDomain);
DirectorySearcher dsUsers = new DirectorySearcher(domain);
dsUsers.Filter = "(userPrincipalName=" + ddlAdsuser.Text + ")";
foreach (SearchResult sResultSet in dsUsers.FindAll())
{
lblfname.Text = GetProperty(sResultSet, "givenName");
lbllname.Text = GetProperty(sResultSet, "sn");
lblemail.Text = GetProperty(sResultSet, "mail");
string Manager = string.Empty;
Manager = GetProperty(sResultSet, "manager");
if (Manager != "")
{
if (Manager.Contains("CN="))
{
int Length = Manager.IndexOf(',');
Manager = Manager.Substring(3, Length - 3);
}
else
{
Manager = string.Empty;
}
}
lblManagerID.Text = Manager; //Here displaying the manager name.
}
}
public static string GetProperty(SearchResult searchResult, string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
{
return searchResult.Properties[PropertyName][0].ToString();
}
else
{
return string.Empty;
}
}
答案 0 :(得分:4)
DirectorySearcher objDirSearch = new DirectorySearcher(SearchRoot);
DirectoryEntry dentUser = null;
string pstrFieldName, pstrValue;
pstrFieldName = "company";
pstrValue = "12345"; //Employee number
/*setting the filter as per the employee number*/
objDirSearch.Filter = "(&(objectClass=user)(" + pstrFieldName + "=" + pstrValue + "))";
SearchResult objResults = objDirectorySearch.FindOne();
dentUser = new DirectoryEntry(objResults.Path);}
string strManager = dentUser.Properties["manager"].Value.ToString();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, strManager);
string strManagerMailID = user.EmailAddress;
答案 1 :(得分:3)
简单的代码,工作得很好:
public static string GetEmail(string userId)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userId);
return user.EmailAddress;
}
您必须添加程序集System.DirectoryServices.AccountManagement.dll。 如果您遇到与AD连接的任何问题,可以尝试在PrincipalContext构造函数中添加AD服务器名称。
答案 2 :(得分:0)
只需再次搜索经理。
请注意,构建查询过滤器的方法有问题,您需要转义一些字符(尤其是"
引号),以避免根据用户输入查询损坏。