Thursday, March 15, 2012

C#.net Check if user is in Active Directory Group


Here is a simple c#.net function to see if a user is in a AD group.

Be sure to add the Directory Services as a refrence to your project and use:

using System.DirectoryServices.AccountManagement;








private static bool IsInGroup(string ingroup)
        {
            string username = Environment.UserName;

            PrincipalContext domainctx = new PrincipalContext(ContextType.Domain,
                                                        "example",
                                                        "DC=example,DC=com");

            UserPrincipal userPrincipal =
                              UserPrincipal.FindByIdentity(domainctx, IdentityType.SamAccountName, username);

            bool isMember = userPrincipal.IsMemberOf(domainctx, IdentityType.Name, ingroup);

            return isMember;
        }

No comments:

Post a Comment

itninja.com