Tuesday, December 22, 2009

SPFile Item Update Error: Operation is not valid due to the current state of the object.

It's very frustrating and can take a whole working day: You are trying to update a library (list) item from Sharepoint object model and getting this error continiously.

In fact, solution is simple: RunWithElevatedPrivileges is working buggy in Sharepoint 2007, so the best things is avoiding putting code in it as much as possible.

For instance, if you want to simply update "Title" of an item in your document library, it should appear like this;

SPFile FileToModify = null;
SPSite ElevatedSite = null;
SPWeb ElevatedWeb = null;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite Site = new SPSite(SiteCollectionUrl))
{
ElevatedWeb = Site.RootWeb;
ElevatedSite = Site;
}
});

SPItem Items = FileToModify.Item;
ElevatedSite.RootWeb.AllowUnsafeUpdates = true;
Items["Title"] = "new title";
FileToModify.Item.UpdateOverwriteVersion();
ElevatedSite.RootWeb.AllowUnsafeUpdates = false;
Returning = "ok";

--

Then you won't face any errors.

No comments: