So I'm trying to access files from a Sharepoint document library in C#. My app is a provider-hosted Sharepoint app. I seem to be able to access the library, but not the library's items.
Here is how I get my context in the controller:
var spContext = SharePointContextProvider.Current.GetSharePointContext(System.Web.HttpContext.Current);
using (var clientContext = spContext?.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
template.SetMergefields(clientContext);
}
}
And how I try to access the files:
Web web = clientContext.Web;
List templateList = web.Lists.GetByTitle(libraryName);
clientContext.Load(templateList);
clientContext.ExecuteQuery();
var templateFiles = templateList.RootFolder.Files;
clientContext.Load(templateFiles);
clientContext.ExecuteQuery();
var templateListItems = templateList.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(templateListItems);
clientContext.ExecuteQuery();
At this point, the templateList
has the property ItemCount = 8
which does match the number of the files in the library. Yet, both templateFiles
and templateListItems
, have Count = 0
so I don't seem to be able to access these 8 items.
I have also tried to access a single item by it's id which I looked up on Sharepoint:
var itemWithId1 = templateList.GetItemById(1);
clientContext.Load(itemWithId1);
clientContext.ExecuteQuery();
Yet this leads to the error:
Microsoft.SharePoint.Client.ServerException: 'Item does not exist. It may have been deleted by another user.'
Another approach I tried was using the GetFileByServerRelativeUrl
to get a specific file:
File file = clientContext.Web.GetFileByServerRelativeUrl(serverRelativeUrl);
clientContext.Load(file);
clientContext.ExecuteQuery();
This gives me the following error:
Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: 'Access denied. You do not have permission to perform this action or access this resource.'
And yes I've checked - I do have full permissions for this library and it's on default settings so item-level permissions do not vary from library's permissions.
Does anyone have an idea what I'm doing wrong or how to do it properly? The actual goal is to access a specific file from the library by the file's name, a file list would also work.