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.





3 comments:
Do we need to check whether the object "web" is null in the "finally" block (like the following)?
finally
{
if (web != null) web.Dispose();
}
tnx a lot , it's working like a charm ,
How does this work when the elevatedSite is disposed of outside the using statement?
Isn't the elevatedRootWeb disposed of at the same time?
Post a Comment