从Active Directory组获取用户电子邮件地址

时间:2010-10-26 16:05:16

标签: .net active-directory

嘿 我需要一些简单的测试程序,它允许我设置AD组名称(例如testdomain.groupname),并根据该组名称检索所有用户(包括子组)的电子邮件地址。

任何代码段都将受到高度赞赏。

由于

1 个答案:

答案 0 :(得分:2)

如果您使用的是.NET 3.5(或者可以升级到它),则可以使用新的System.DirectoryServices.AccountManagement命名空间来轻松实现此目的。

在这里阅读有关新.NET 3.5 gem的更多信息:Managing Directory Security Principals in the .NET Framework 3.5

// create a context - you need to supply your 
// domain NetBIOS-style, e.g. "CONTOSO"
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

// find the group you're interested in
GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctx, "YourGroupName");

// enumerate the members of that group
// the "true" in GetMembers() means: enumerate recursively, e.g.
// if another group is found as member, its members are enumerated
PrincipalSearchResult<Principal> members = gp.GetMembers(true);

// iterate over the principals found
foreach(Principal p in members)
{
    // test to see if it's a UserPrincipal
    UserPrincipal up = (p as UserPrincipal);

    if (up != null)
    {
         // if it is - set the new e-mail address
         up.EmailAddress = "yournewemail@yourdomain.com";
         up.Save();
    }
}