07 January, 2008

Iterating Over and Deleting SharePoint Groups Programmatically

Ever wanted to do something with the groups within SharePoint 2007 programmatically? Here is some sample code you might find useful.

Iterating:

public IListstring> GetAllUserGroups(string url)
{
    IListstring> groupList = new Liststring>();

    using (SPSite site = new SPSite(url))
    {
        SPGroupCollection groups = site.RootWeb.SiteGroups;
        foreach (SPGroup g in groups)
        {
            groupList.Add(g.Name);
        }
    }

    return groupList;
}

Deleting:

public void DeleteUserGroups(IListstring> GroupNames, string url)
{
    using (SPSite site = new SPSite(url))
    {
        SPGroupCollection groups = site.RootWeb.SiteGroups;

        foreach (string groupname in GroupNames)
        {
            groups.Remove(groupname);
        }
    }
}

That code sure could do with some error handling around the remove statement.


Tags: