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

C#.net Check if user is in Active Directory Group
Photo by Luca Bravo / Unsplash

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 reference to your project and use:

using System.DirectoryServices.AccountManagement;


        public string GetDomain()
        {

            return Environment.UserDomainName.ToString();


        }



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

            var domainctx = new PrincipalContext(ContextType.Domain, GetDomain());
            var userPrincipal = UserPrincipal.FindByIdentity(domainctx, IdentityType.SamAccountName, username);

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

            return isMember;
        }