Tuesday, March 27, 2012

Add List Items with users identity (Created By) when using RunWithElevatedPriviledges delegate

We faced a situation when we have to elevate the read only users permission to add/update the list items in SharePoint list. To accomplish this we usually go for the RunWithElevatedPriviledges delegate, but the only disadvantage of this approach is if we add/update any item within this delegate, it will save that record with 'System Account' identity.

Following code can be used to overwrite the 'System Account' identity with current user's identity, So list item will display 'Created By' or 'Modified By' columns value as current user.

SPUser user = SPContext.Current.Web.CurrentUser;

    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
        using (SPWeb web = site.OpenWeb())
            web.AllowUnsafeUpdates = true;
            SPList list = web.Lists["TempList"];
            SPListItem listItem = list.AddItem();
            listItem["Title"] = string.Format("Hey {0}", user.LoginName);
            listItem["Editor"] = user;  // Modified By                    
            listItem["Author"] = user;  // Created By
            web.AllowUnsafeUpdates = false;

No comments:

Post a Comment