C # get groups a user belongs to in Active Directory
I am not a programmer by nature, so I apologize in advance :) I am using code snippets from http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via -C # 39. and it was really helpful. I am using his method to get user group memberships and it also requires a method AttributeValuesMultiString
. I don't have any syntax errors, but when I call the Groups
method with Groups("username", true)
, I get the following error:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in System.DirectoryServices.dll
I dug around a bit but it doesn't seem to give an answer as to why I am getting this error.
source to share
You should check the namespace System.DirectoryServices.AccountManagement
(S.DS.AM). Read more here:
- Managing Directory Security Principles in the .NET Framework 3.5
- MSDN Docs at 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 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 very easy to play with users and groups in AD!
source to share