By using the SPUser.Groups property you can easily enumerate the groups that a user has been assigned to. However one problem with this approach is that if the user is a member of a domain group that has been allocated to a SharePoint group, then this group does not appear in SPUser.Groups. e.g. say that a user account is assigned to SharePoint groups SP1, SP2 and SP3 and that the user is a member of an AD group, ADGroup1, which in turn is assigned to SharePoint group SP4. When enumerating SPUser.Groups only SP1, SP2, and SP3 will be listed even though the user is a member of SP4 indirectly via his membership of the ADGroup1 group.
So, how can we ascertain whether a particular user is a member of the SharePoint group or not, taking into account AD group membership ? The short answer is use the SPGroup.ContainsCurrentUser property as shown below:
string siteUrl = "http://localhost"
string userName = "DOMAIN\\username";
string groupName = "SharePoint Test Group";
SPSite siteCollection = new SPSite(siteUrl);
SPWeb site = siteCollection.OpenWeb();
SPGroup testGroup = site.Groups[groupName];
if (testGroup != null)
{
Console.WriteLine(
String.Format("Is current user in group={0}",
testGroup.ContainsCurrentUser.ToString()));
}
Obviously this only tells you whether the user account running the current context is a member of the group or not. In order to ascertain whether a different user is in the group you'll need to create an SPSite object using the appropriate SPUserToken to give you the appropriate context to use. An example can be seen below:
string siteUrl = " http://localhost ";
string userName = "DOMAIN\\anotheruser";
string groupName = "SharePoint Test Group";
SPSite siteCollection = new SPSite(siteUrl);
SPWeb site = siteCollection.OpenWeb();
SPUserToken userToken = site.AllUsers[userName].UserToken;
// Use an SPSite and SPWeb that have the context of the appropriate user
using (SPSite contextSiteColl = new
SPSite(siteUrl, userToken))
{
using (SPWeb contextSite = contextSiteColl.OpenWeb())
{
SPGroup testGroup = contextSite.Groups[groupName];
Console.WriteLine(String.Format("Username = {0}, got group {1}.",
userName, groupName));
if (testGroup != null)
{
Console.WriteLine(String.Format("Is current user in group={0}",
testGroup.ContainsCurrentUser.ToString()));
}
}
}