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 IList<string> GetAllUserGroups(string url)
{
    IList<string> groupList = new List<string>();

    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(IList<string> 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.