Translate

Sunday, August 26, 2012

Using RunWithElevatedPrivileges or SPSecurity.RunWithElevatedPrivileges

Using RunWithElevatedPrivileges or SPSecurity.RunWithElevatedPrivileges


"RunWithElevatedPrivileges" method accepts a delegate code which wants to run with administrator’s privileges, actually the code runs under the application pool identity, which is mainly site collection administrator.
The namespace SPSecurity  is required for  RunWithElevatedPrivileges
Sample code shows the item updated code which runs in the SPSecurity.RunWithElevatedPrivileges
Code:
SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite mySite = new SPSite(“site url”);//mention site url
                 mySite.AllowUnsafeUpdates = true;
                 SPWeb spweb = mySite.OpenWeb();
                 spweb.AllowUnsafeUpdates = true;
                 SPList myList = spweb.Lists[“Demo List”];
                 SPListItem spNewItem = myList.Items.Add();
                 spNewItem["Title"] = “Test Title”;
                 spNewItem.Update();
});

No comments:

Post a Comment