Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 593613
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T15:51:52+00:00 2026-05-13T15:51:52+00:00

How do i go about iterating a group to find out if a given

  • 0

How do i go about iterating a group to find out if a given user is a member of a group?

I know i can use IsInRole on WindowsPrincipal object but for some reason it don’t always work for me, it doesn’t error out or throw exception but just return false.

i have put together following code from web, can some help me improve it in terms of reliability, it hasn’t gave any wrong result in 3 weeks of testing.

Side notes: 1: I don’t have access to AD username and password hence using GC. 2: Groups can be created in any domain but with in same forest. 3: Group can have users from various domains as well as groups.

thanks

KA

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
    static extern int CheckTokenMembership(int TokenHandle, byte[] PSID, out bool IsMember);

   [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
    static extern bool IsValidSid(byte[] PSID);


private bool Authenticate(XmlNodeList XmlNodeGroups)
    {
        bool result = false;
        try
        {
            Dictionary<string, List<string>> Groups = GetGroups(XmlNodeGroups);
            //search global catalog and get SID of the group
            Byte[] sid = null;
            foreach (string groupName in Groups.Keys)
            {
                using (DirectoryEntry entry = new DirectoryEntry("GC:"))
                {
                    IEnumerator ie = entry.Children.GetEnumerator();
                    ie.MoveNext();
                    using (DirectorySearcher ds = new DirectorySearcher((DirectoryEntry)ie.Current))
                    {
                        ds.Filter = string.Format("(&(|(sAMAccountName={0}))(objectClass=group))", groupName);  
                        using (SearchResultCollection resColl = ds.FindAll())
                        {
                            if (resColl.Count > 0)
                            {
                                ResultPropertyCollection resultPropColl = resColl[0].Properties;
                                sid = (byte[])resultPropColl["objectsid"][0];
                                if (sid == null || !IsValidSid(sid))
                                {
                                    // log message and continue to next group                                        continue;
                                }
                            }
                            else
                            {
                                  // log message and continue to next group                                    continue;
                            }
                        }

                        bool bIsMember = false;
                        if (CheckTokenMembership(0, sid, out bIsMember) == 0)
                        {
                               // log message and initiate fall back....... use Legacy
                            result = CheckMemberOf(XmlNodeGroups, _CurrentIdentity);
                            break;
                        }
                        else
                        {
                            result = bIsMember ? true : false;
                            if (result)
                            {
                                // debug message                                    break;
                            }
                            else
                            {
                               // debug message
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // log exception message and initiate fall back....... use Legacy
            result = CheckMemberOf(XmlNodeGroups, _CurrentIdentity);
        }
        return result;
    }</code>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T15:51:53+00:00Added an answer on May 13, 2026 at 3:51 pm

    Are you on .NET 3.5 ? If so, check out the MSDN magazine article Managing Directory Security Principals in the .NET Framework 3.5. It shows just how much easier things have become when it comes to users and groups in AD.

    As for your requirement – you could

    • find the group in question
    • enumerate all its members
    • find if your given user is a member in that group

    and all this can be done quite easily with the help of the System.DirectoryServices.AccountManagement namespace:

    // establish a context - define a domain (NetBIOS style name),  
    // or use the current one, when not specifying a specific domain
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    
    // find the group in question
    GroupPrincipal theGroup = GroupPrincipal.FindByIdentity(ctx, "nameOfGroup");
    
    // recursively enumerate the members of the group; making the search
    // recursive will also enumerate the members of any nested groups
    PrincipalSearchResult<Principal> result = theGroup.GetMembers(true);
    
    // find the user in the list of group members
    UserPrincipal user = (result.FirstOrDefault(p => p.DisplayName == "Some Name") as UserPrincipal);
    
    // if found --> user is member of this group, either directly or recursively
    if(user != null)
    {
         // do something with the user
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.