Friday, September 5, 2008

Error - Operation is not valid due to the current state of the object. SPListItem and RunWithElevatedPrivileges

When trying to update a SPListItem inside a SPSecurity.RunWithElevatedPrivileges block, you will received the following error: Operation is not valid due to the current state of the object.

So if you are doing something like this:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = new SPSite(sURL).OpenWeb())
{
SPList list = web.Lists["MyList"];
//add a folder
SPListItem listItem = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, sFolderName);

listItem.Properties["Name"] = sFolderName;

listItem.Update(); //and boom goes the dynamite!
}
}
);


You will now have to switch it up and do something like this:



SPWeb web = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(sURL))
{
web = site.OpenWeb();
}
}
);

SPList list = web.Lists["MyList"];
//add a folder
SPListItem listItem = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, sFolderName);

listItem.Properties["Name"] = sFolderName;
listItem.Update(); //update is successful
}
catch
{
}
finally
{
web.Dispose();
}

Only setting the SPWeb object in the RunWithElevatedPrivileges block will avoid this error from happening.