When i trying to delete listItem from list and anonymous access in site perm(for Fund3) is disabled my code throw exception. Where anonymous access is enable everything is OKAY-> items are deleted.....
Exception:
Error message: System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) at Microsoft.SharePoint.SPGlobal.HandleUnauthorizedAccessException(Unauthoriz edAccessException ex) at Microsoft.SharePoint.Library.SPRequest.GetListsWithCallback(String bstrUrl , Guid foreignWebId, String bstrListInternalName, Int32 dwBaseType, Int32 dwBase TypeAlt, Int32 dwServerTemplate, UInt32 dwGetListFlags, UInt32 dwListFilterFlags , Boolean bPrefetchMetaData, Boolean bSecurityTr Error stackTrace: at Microso ft.SharePoint.SPGlobal.HandleComException(COMException comEx) at Microsoft.SharePoint.Library.SPRequest.DeleteItem(String bstrUrl, String b strListName, Int32 lID, UInt32 dwDeleteOp, Boolean bUnRestrictedUpdateInProgress , Guid& pgDeleteTransactionId) at Microsoft.SharePoint.SPListItem.DeleteCore(DeleteOp deleteOp) at Microsoft.SharePoint.SPListItem.Delete() at ClearLibsInFund.Program.b__0()
My code:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
try
{
using (var oSite = new SPSite(args[0])) //argument for Console application
{
using (var oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
var list = oWeb.Lists.TryGetList(listName);
var queryItems = new SPQuery();
queryItems.ViewXml = "<View Scope='Recursive'></View>";
var items = list.GetItems(queryItems);
//Option 1
for (int i = items.Count - 1; i >= 0; i--)
{
items[i].Recycle();
}
//Option 2
//foreach (SPListItem listitem in items)
//{
// SPListItem itemToDelete = list.GetItemById(listitem.ID);
// itemToDelete.Recycle();
//}
//Option 3
//while (items.Count > 0)
//{
// items[0].Recycle();
//}
oWeb.AllowUnsafeUpdates = false;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error message: " + ex.Message + " Error stackTrace: " + ex.StackTrace);
}
});
Where is the problem, because i run code with RunWithElevatedPrivileges and which option to delete must use(best practice)...