Freigeben über


Getting a List of a User’s SharePoint Groups

I found it very odd that this was not available when doing some search engine queries.  My requirement was to take in an AD user name and query SharePoint 2010 to determine the SharePoint groups in which the account belongs.  The code was to run from within a RIA Authentication Service, which is code run on a server and is not likely on the SharePoint server.  This code will also work with SharePoint 2007 (WSS 3.0 and MOSS 2007).  You will need to add a Web Reference to http(s)://<spservername>/_vti_bin/usergroup.asmx and name it SharePointUserGroupService.  Voila, you have your list of SharePoint groups for a user.  Maybe in the next version of the SharePoint Client Object Models (SCOM) this will be included.  It does required LINQ support (.NET 3.5 or greater) where this code is run (not necessarily on the server).

    1: private string[] GetRoles(string userName)
    2: {
    3:     UserGroup userGroupService = new UserGroup();
    4:     userGroupService.UseDefaultCredentials = true;
    5:     XmlNode xNode = userGroupService.GetGroupCollectionFromUser(userName);
    6:  
    7:     XElement groupXml = XElement.Parse(xNode.OuterXml);
    8:  
    9:     XNamespace ns = groupXml.Name.Namespace;
   10:  
   11:     var item = from xml in groupXml.Elements(ns + "Groups").Elements(ns + "Group")
   12:                let GroupName = (string)xml.Attribute("Name")
   13:                select GroupName; 
   14:  
   15:     return item.ToArray();
   16:  
   17: }