How to check if a user belongs to an AD group?

Since you're on .NET 3.5 and up, 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
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME");

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

if(user != null)
{
   // check if user is member of that group
   if (user.IsMemberOf(group))
   {
     // do something.....
   } 
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!


Check if current user in a group

public bool AuthenticateGroup(string groupfind)
        {
            var p = new Process();
            StringBuilder stringbd = new StringBuilder();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = @"/c gpresult /V";
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = false;
            p.StartInfo.UseShellExecute = false;
            p.OutputDataReceived += (a, b) => stringbd.AppendLine(b.Data);
            p.ErrorDataReceived += (a, b) => stringbd.AppendLine(b.Data);
            p.Start();
            p.BeginErrorReadLine();
            p.BeginOutputReadLine();
            p.WaitForExit();
            var textfind = stringbd.ToString();
            int findpoint = textfind.IndexOf("The user is a part of");
            string findgroup = "";
            if (findpoint > 0)
            {
                findgroup = textfind.Substring(findpoint, textfind.Length - findpoint);
            }

            return findgroup.Split('\n').ToList().Any(r=>r.Trim().ToLower()==groupfind.Trim().ToLower());
        }

Slight deviation from @marc_s example, implemented in the static void Main() method in Program:

DomainCtx = new PrincipalContext( ContextType.Domain , Environment.UserDomainName );
if ( DomainCtx != null ) {
    User = UserPrincipal.FindByIdentity( DomainCtx , Environment.UserName );
}

DomainCtx and User are both static properties declared under Program

Then in other forms i simply do something like this:

if ( Program.User.IsMemberOf(GroupPrincipal.FindByIdentity(Program.DomainCtx, "IT-All") )) {
    //Enable certain Form Buttons and objects for IT Users

}