I've found the various "Associated..." properties to often be NULL. The only reliable way is to use the property bag on the SPWeb:
- Visitors:
vti_associatevisitorgroup
- Members:
vti_associatemembergroup
- Owners:
vti_associateownergroup
To convert them to an SPGroup object, you could use:
int idOfGroup = Convert.ToInt32(web.Properties["vti_associatemembergroup"]);
SPGroup group = web.SiteGroups.GetByID(idOfGroup);
However as Kevin mentions, the associations may be lost which would throw exceptions in the above code. A better approach is to:
Check that associations have been set on the web by ensuring the property you are looking for actually exists.
Check that the group with ID given by the property actually exists. Remove the call to SiteGroups.GetByID and instead loop through each SPGroup in SiteGroups looking for the ID.
The more robust solution:
public static SPGroup GetMembersGroup(SPWeb web)
{
if (web.Properties["vti_associatemembergroup"] != null)
{
string idOfMemberGroup = web.Properties["vti_associatemembergroup"];
int memberGroupId = Convert.ToInt32(idOfMemberGroup);
foreach (SPGroup group in web.SiteGroups)
{
if (group.ID == memberGroupId)
{
return group;
}
}
}
return null;
}