How to: Determine all Audiences a User is a Member of in a Web
Applies to: SharePoint Server 2010
This example shows you how to use the Audience object model to determine all the audiences a user is a member of in a given Web. Note that the results include all Microsoft Exchange distribution lists (DL), SharePoint groups, global audiences, and rules-based audiences.
The AudienceType enumeration represents the type of the audience to which a user belongs. The enumeration value can be:
DL
Global
SharePointGroup
Replace servername and other placeholder strings with actual values before using this example. Also add the following references to your Microsoft Visual Studio project:
Microsoft.Office.Server
Microsoft.Office.Server.UserProfiles
Microsoft.SharePoint
System.Web
Example
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server.Audience;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using System.Web;
using System.Collections;
namespace AudienceConsoleApp
{
class Program
{
static void Main(string[] args)
{
try
{
using (SPSite site = new SPSite("https://servername"))
{
SPServiceContext context = SPServiceContext.GetContext(site);
AudienceManager AudMgr = new AudienceManager(context);
SPWeb web = site.AllWebs[0];
try
{
ArrayList audienceIDNames = AudMgr.GetUserAudienceIDs("domainname\\username", true, web);
ArrayList audienceNames = new ArrayList();
for (int i = 0; i < audienceIDNames.Count; i++)
{
AudienceNameID arrTemp = (AudienceNameID)audienceIDNames[i];
audienceNames.Add(arrTemp.AudienceName);
Console.WriteLine(audienceNames[i].ToString());
}
Console.Read();
}
catch (AudienceException e)
{
//Your exception handling code here
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
Console.Read();
}
}
}
}