如何在C#中通过AD组名查询Active Directory组邮箱或通过邮箱反查组名
你当前使用的GroupPrincipal类默认未公开邮件属性,AD组的邮箱地址存储在底层目录对象的mail扩展属性中,需要通过获取关联的DirectoryEntry实例读取对应值。
按AD组名称查询对应邮箱
完整实现代码如下:
using System.DirectoryServices; using System.DirectoryServices.AccountManagement; // 初始化AD域上下文 PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // 按名称查找目标AD组,替换为你要查询的组名"Stack Over Flow IT" GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "Stack Over Flow IT"); if (group != null) { // 获取底层目录对象以读取扩展属性 DirectoryEntry dirEntry = group.GetUnderlyingObject() as DirectoryEntry; if (dirEntry.Properties.Contains("mail")) { string groupEmail = dirEntry.Properties["mail"].Value.ToString(); // 输出结果为类似stackoverflowit@stackoverflow.com的邮箱格式 Console.WriteLine(groupEmail); } else { Console.WriteLine("该AD组未配置邮箱地址"); } }
按AD组邮箱反向查询组名称
使用LDAP过滤器定向查询匹配指定邮箱的AD组即可,实现代码如下:
using System.DirectoryServices; using System.DirectoryServices.AccountManagement; // 替换为你要查询的目标组邮箱 string targetEmail = "stackoverflowit@stackoverflow.com"; PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // 构造查询过滤器 GroupPrincipal filter = new GroupPrincipal(ctx); PrincipalSearcher searcher = new PrincipalSearcher(filter); DirectorySearcher dirSearcher = searcher.GetUnderlyingSearcher() as DirectorySearcher; // 设置LDAP查询条件,仅匹配指定邮箱的组对象 dirSearcher.Filter = $"(&(objectCategory=group)(mail={targetEmail}))"; dirSearcher.PropertiesToLoad.Add("name"); SearchResult result = dirSearcher.FindOne(); if (result != null) { string groupName = result.Properties["name"][0].ToString(); // 输出匹配的AD组名称 Console.WriteLine(groupName); } else { Console.WriteLine("未找到匹配该邮箱的AD组"); }
注意事项
- 运行代码的身份需要具备AD域的只读访问权限,否则会触发权限不足的异常
- 只有启用邮件功能的AD组才会存在
mail属性,未配置邮件的组查询结果为空,需做好空值判断 - 多域环境下需要在
PrincipalContext初始化时指定对应域的域名,避免跨域查询失败
内容的提问来源于stack exchange,提问作者Rangarajakrishnan
相关产品推荐
相关产品推荐

