Wednesday, May 11, 2011

Making entry for a user in elevated privileges mode

Scenario:
This is quick snippet to show how to make a entry in Custom List on behalf of the user , even in elevated privileged mode.

Code:

 SPContext.Current.Web.AllowUnsafeUpdates = true;

SPUser user = SPContext.Current.Web.CurrentUser;
string weburl = SPContext.Current.Web.Url;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(weburl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["test list"];
SPListItem listItem = list.Items.Add();
listItem["Title"] = string.Format("I am {0}", user.LoginName);
// Modified By
listItem["Editor"] = user;
// Created By
listItem["Author"] = user;
listItem.Update();
}
}
}
);
SPContext.Current.Web.AllowUnsafeUpdates = false;
Update: My good friend Venkat mentioned that in case of update we should not update 'Author'

2 comments:

Anonymous,  August 9, 2011 at 2:44 AM  

Good Post.

Thanks!

Anonymous,  August 22, 2013 at 9:38 AM  

Thank you!! Was stuck on this one for a while