C# get groups that a user is a member of in Active Directory
You should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
- Managing Directory Security Principals in the .NET Framework 3.5
- MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in 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!
msindle
Updated on June 29, 2022Comments
-
msindle almost 2 years
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. I'm using his method for getting user group memberships and it requires his
AttributeValuesMultiString
method as well. I don't have any syntax errors but when I call theGroups
method viaGroups("username", true)
I get the following error:An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in System.DirectoryServices.dll
I have done some digging but nothing seems to really answer why I'm getting this error.
-
Joe over 9 yearsI agree S.DS.AM is simpler - when it works. But be aware that it has bugs that Microsoft seems unable / unwilling to fix: connect.microsoft.com/VisualStudio/feedbackdetail/view/748790/…
-
Cody over 8 yearsI always come back to having inconsistent issues with the AccountManagement DLL. It's a nightmare.
-
JsonStatham about 5 years@marc-s What if you want the groups that ARE NOT authorisation groups
-
Shruti almost 5 years@JsonStatham: On the user object, there is another function called user.GetGroups(). Maybe thats what you were looking for.