Operation is not valid due to the current state of the object by adding SPFolder or SPListItem

hey guys,

The error described above is one of the common errors which we get when developing with SharePoint Object model. 

In my case the Error came up because of SPFolder "Update" using the "RunWithElevatePrivilege" method as below:

SPSecurity.RunWithElevatedPrivileges(delegate{
using (SPSite site = new SPSite("http://mySiteUrl"))
{
using (SPWeb web = site.OpenWeb())
{

SPFolder newFolder = web.Lists[listName].RootFolder.SubFolders.Add(folderUrl);

newFolder.Update();

web.Update();

}
}

});

To resolve this issue you must update your Item or Folder outside of the ElevatedPrivileges Construct as below:

 

SPSite site = null; SPWeb web = null

SPSecurity.RunWithElevatedPrivileges(delegate(){

site = new SPSite(m_SharePointSiteURL);

web = site.OpenWeb(m_SharePointWebName); });

SPFolder newFolder = web.Lists[listName].RootFolder.SubFolders.Add(folderUrl);

newFolder.Update();

web.Update();

if (web != null) web.Dispose();

if (site != null) site.Dispose();

 

 cheers


Posted Mar 29 2010, 03:43 PM by Nadine Storandt
Filed under: ,

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
developers.de is a .Net Community Blog powered by daenet GmbH.