Find all SharePoint groups an AD user is member of


It’s quite easy to find the SharePoint groups each user is member of by object model. SPUser.Groups will give you the collection of groups the user is member of. But if this user is a member of an AD group and that AD group is added as a member of the SharePoint group then that SharePoint group will not reflect in the SPUser.Groups.


Here is the code showing how to do it. It is applicable for both SharePoint 2007 and 2010. But only for those users using standard Windows Authentication:


using System;
using System.Collections.Generic;
using System.Collections;
using System.DirectoryServices;
using System.Text;
using Microsoft.SharePoint;


namespace ConsoleAppFindUserGroups
{
    class Program
    {
        static void Main(string[] args)
        {


            using (SPSite site = new SPSite("http://moss.litwareinc.com"))
            {
                SPWeb web = site.OpenWeb();
                SPUser user = web.AllUsers[args[0]];
                SPGroupCollection groupCol = user.Groups;
                foreach (SPGroup group in groupCol)
                {
                    Console.WriteLine(group.Name + "\n");
                }
                DirectoryEntry de = new DirectoryEntry("LDAP://CN=users;DC=Litwareinc;DC=com");
                de.AuthenticationType = AuthenticationTypes.Secure;
                DirectorySearcher deSearch = new DirectorySearcher(de);
                string userName = args[0].Substring(args[0].LastIndexOf('\\') + 1);
                deSearch.Filter = "(SAMAccountName=" + userName + ")";
                SearchResult results = deSearch.FindOne();
                DirectoryEntry obUser = new DirectoryEntry(results.Path);
                object obGroups = obUser.Invoke("Groups", null);
                foreach (object ob in (IEnumerable)obGroups)
                {
                    DirectoryEntry obGroupEntry = new DirectoryEntry(ob);
                    string groupName = obGroupEntry.Name;
                    int equalsIndex = groupName.IndexOf("=", 1);
                    groupName = groupName.Substring(equalsIndex + 1);
                        foreach ( SPGroup spGroup in web.Groups)
                        {
                            foreach (SPUser spUser in spGroup.Users)
                            {
                                if (spUser.Name == groupName)
                                {
                                    Console.WriteLine(spGroup.Name + "\n");
                                }
                            }
                        }                  
                }
                Console.ReadLine();
            }
           
        }
    }
}


Comments (1)

  1. Neil says:

    Hi, I'm new to Sharepoint development. This solution really works for me but how should i deploy this? THanks

Skip to main content