简体   繁体   English

C# 获取用户在 Active Directory 中所属的组

[英]C# get groups that a user is a member of in Active Directory

I'm not a programmer by nature so I apologize in advance :) I'm using the code snippets from http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C#39 and it has been really helpful.我天生不是程序员,所以我提前道歉:) 我正在使用来自http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via的代码片段-C#39 ,它真的很有帮助。 I'm using his method for getting user group memberships and it requires his AttributeValuesMultiString method as well.我正在使用他的方法来获取用户组成员资格,并且还需要他的AttributeValuesMultiString方法。 I don't have any syntax errors but when I call the Groups method via Groups("username", true) I get the following error:我没有任何语法错误,但是当我通过Groups("username", true)调用Groups方法时Groups("username", true)出现以下错误:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in System.DirectoryServices.dll System.DirectoryServices.dll 中发生类型为“System.Runtime.InteropServices.COMException”的未处理异常

I have done some digging but nothing seems to really answer why I'm getting this error.我已经做了一些挖掘,但似乎没有什么能真正回答我为什么会收到这个错误。

You should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace.您应该查看System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。 Read all about it here:在这里阅读所有相关信息:

Basically, you can define a domain context and easily find users and/or groups in AD:基本上,您可以定义域上下文并轻松找到 AD 中的用户和/或组:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // get the user's groups
       var groups = user.GetAuthorizationGroups();

       foreach(GroupPrincipal group in groups)
       {
           // do whatever you need to do with those groups
       }
    }

}

The new S.DS.AM makes it really easy to play around with users and groups in AD!新的 S.DS.AM 使在 AD 中与用户和组一起玩变得非常容易!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM