title: Change permission level for groups programmatically in SharePoint 2010?
body: <p>I want to loop through all  the sites in a site collection and change the permission for a certain site.</p>
  
  <p>My code is:</p>
  
  <pre><code>        SPSite oSiteCollection = SPContext.Current.Site;
          SPWebCollection collWebsite = oSiteCollection.AllWebs;
          foreach (SPWeb web in collWebsite)
          {
              web.AllowUnsafeUpdates = true;
  
              if (web.Name == "SiteName")
              {
                  web.BreakRoleInheritance(true);
  
                  string[] groups = new string[2] { "Group1", "Group2" };
  
                  foreach (string item in groups)
                  {
                      SPGroup removeGroup = web.SiteGroups[item];
                      web.RoleAssignments.Remove(removeGroup);
  
                      SPGroup addGroup = web.SiteGroups[item];
                      SPRoleDefinition roleDefinition = web.RoleDefinitions["Read"];
                      SPRoleAssignment roleAssignment = new SPRoleAssignment(addGroup);
                      roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                      web.RoleAssignments.Add(roleAssignment);
                  }
              }
  
          }
  </code></pre>
  
  <p>but it gives me an error</p>
  
  <pre><code>Error changing permissions, details: There are uncommitted changes on the SPWeb object, call SPWeb.Update() to commit the changes before calling this method.
  </code></pre>
  
  <p>The code works just fine if I want to do the same but for lists instead</p>
  
  <pre><code>            SPListCollection collList = web.Lists;
  
              foreach (SPList oList in collList)
              {
                  //and so on
  </code></pre>
  
  <p>I have tried to put web.Update() in various places but without success. Any ideas?</p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>I commented out most of the stuff and only left</p>
  
  <pre><code>        if (web.Name == "SiteName")
          {
              web.BreakRoleInheritance(true);
              web.Update();
          }
  </code></pre>
  
  <p>but it still throws the same error.</p>