Elevating Privileges in SharePoint

Here’s a good tip for elevating privileges in SharePoint.


For those who doesn’t want to click on that link (like myself when I searching for this post again), here’s the code.

//Don't dispose the following two objects. Sharepoint will take care of their disposal when page is completely rendered.
SPWeb  webInUserContext = SPContext.Current.Web;
SPSite SiteInUserContext = SPContext.Current.Site;
Guid webGuid = webInUserContext.ID;
Guid siteGuid = SiteInUserContext.ID;

                    // get the site in impersonated context
                    using (SPSite site = new SPSite(siteGuid))

                        // get the web in the impersonated context
                        SPWeb web = site.OpenWeb(webGuid);
                       // Do your work here  



There we go. I used this piece of code to access the SPFile of a document within SharePoint. SPFile requires elevated privileges, and can’t be access with just your normal privileges.

My code works now, and I’m happy. :)