Skip to main content

List all SharePoint groups a user belongs to

This is just a small Utility requested on one of the SharePoint Newsgroups.
It uses the UserGroup web service to list all the SharePoint Groups a user belongs to in a specified Site Collection.

It’s a small console application which requires two parameters:

using System;
using System.IO;
using System.Xml;
using ListUsersGroups.ug;
  
namespace ListUsersGroups
{
    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length < 2)
                return help();
            try
            {
                UserGroup usergroup = new UserGroup();
                usergroup.UseDefaultCredentials = true;
                usergroup.Url = args[0]+"/_vti_bin/usergroup.asmx";;
                XmlNode groupXml =usergroup.GetGroupCollectionFromUser(args[1]);
                XmlDocument doc = new XmlDocument();
                doc.Load(new XmlNodeReader(groupXml));
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("sp", "<a href="http://schemas.microsoft.com/sharepoint/soap/directory/">http://schemas.microsoft.com/sharepoint/soap/directory/</a>");
                foreach (XmlNode group in doc.SelectNodes("//sp:Groups/sp:Group";, nsmgr))
                    Console.WriteLine(group.Attributes[&quot;Name&quot;].Value);
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}\r\n{1}";, ex.Message, ex.StackTrace);
            }
            return 0;
        }
 
        private static int help()
        {
            Console.WriteLine(@"{0} ", Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]));
            Console.WriteLine(@"  Site-url: Url of site collection including protocol (example 
      <a>http://localhost)"</a>);
            Console.WriteLine(@"  username: Full username including domain (example MOSSWORK\user)");
            return -1;
        }
    }
}

The execuable can be found here and the source code here

Copyright © 2007-2022