Enumeration of nested AD user groups using C#

帅比萌擦擦* 提交于 2019-12-03 16:21:45

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // get a user's group memberships 
   foreach(Principal principal in me.GetGroups())
   {
       GroupPrincipal gp = (principal as GroupPrincipal);

       if(gp != null)
       {
           // do something with the group
       }
   }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD. The call to .GetGroups() also handles all the problems of nested group memberships and so forth for you - no need to deal with that hassle anymore!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!