You could use the SPSecurity.RunWithElevatedPrivileges method which uses impersonation i.e means to execute the code, it has higher access (application pool account) than the logged-in actual user.
Example:
SPSite site = new SPSite("siteURL");
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//using (SPWeb web = site.OpenWeb())
//{
//string user = web.CurrentUser.Name;
//Operations that need high level access.
//}
Inject all your code here.
});
Refer to the below articles for how to use this:
Impersonation and Elevation of Privilege
When and How to Use Run With Elevated Privileges (RWEP) in SharePoint
How to use SPSecurity.RunWithElevatedPrivileges in event receiver Example ?
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace SharePoint.Development.EventReceivers
{
///
/// List Item Events
///
public class ItemCheckedInEventReceiver : SPItemEventReceiver
{
private string newDocumentUrlExample = "http://newfilelocation/document.doc";
public override void ItemCheckedIn(SPItemEventProperties properties)
{
base.EventFiringEnabled = false; // Disable event receiver firing so that we do not accidentally kick off a different thread
try
{
// Check if user has a certain set of permissions, i.e. can they delete items? if not, then we will have to RunWithElevatedPrevileges
if (properties.Web.DoesUserHavePermissions(properties.UserLoginName, SPBasePermissions.DeleteListItems))
{
SPFile file = properties.ListItem.File; // Get the file
file.MoveTo(newDocumentUrlExample); // Move it to the new location
}
else
{
RunWithElevatedPrivileges(properties, newDocumentUrlExample); // User doesn't have required permissions and therefore the code must be executed with Elevated perms.
}
}
catch (Exception exception)
{
// Write exception to ULS and Event Logs
}
finally
{
base.EventFiringEnabled = true;
}
}
public static void RunWithElevatedPrivileges(SPItemEventProperties properties, string newURL)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
// Everything executed here will be executed under the AppPool account and will have full permissions.. so becareful!!
using (SPSite site = new SPSite(properties.SiteId))
{
using (SPWeb web = site.OpenWeb(properties.Web.ID))
{
SPList list = web.Lists[properties.ListId];
SPListItem listItem = list.Items.GetItemById(properties.ListItemId);
SPFile file = listItem.File;
file.MoveTo(newURL);
}
}
});
}
catch (Exception exception)
{
// Write exception to ULS and Event Logs
}
}
}
Reference:
Execute Code In SharePoint With Elevated Privileges