Reputation:
I have a sharepoint list where i want to get my datas but when i try to access it by code it says to me "Access Denied" and with "Elevated Privilege" i can see i have 614 items (by using items.ItemCount not items.count ) in it but when i try to get them i can't.
Here is the code i'm using
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using(SPSite site = new SPSite("http://mysite/"))
{
using(SPWeb web = site.OpenWeb())
{
SPQuery query = new SPQuery();
SPList list = web.Lists["mylist"];
SPListItemCollection items = list.Items;
for (int i = 0;i <list.ItemCount; i++)
{
Console.WriteLine(items[i].Name);
}
}
}
});
I also tried to use the getitems(query) like this
SPListItemCollection items = list.GetItems(query);
The result is the same. (Note that the query works in CAML Builder)
Upvotes: 1
Views: 776
Reputation: 353
The code inside SPSecurity.RunWithElevatedPrivileges block runs under the Application Pool Account of your web application.This permission should suffice in most cases to overcome all security restrictions.
In your case if the app pool account doesnt have any permission to that site collection, it will throw access denied.I would suggest trying impersonating a site collection administrator like below,
SPUserToken token = oWeb.AllUsers["[AdministratorLoginName]"].UserToken;
using(SPSite site = new SPSite("http://mysite/",token))
{
using(SPWeb web = site.OpenWeb())
{
SPQuery query = new SPQuery();
SPList list = web.Lists["mylist"];
SPListItemCollection items = list.Items;
for (int i = 0;i <list.ItemCount; i++)
{
Console.WriteLine(items[i].Name);
}
}
}
Upvotes: 1