Search code examples
c#asp.net-mvcsharepointmicrosoft-graph-apimicrosoft-graph-sdks

Graph Items.GetAsync() requires Filter opposite to Documentation


I want to list all items from a Sharepoint Document Library as shown below:

var dokumenteId = "The Id of the document library";

var options = new TokenCredentialOptions
{
 AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};

var clientSecretCredential = new ClientSecretCredential(_tenantId, _clientId, _clientSecret, options);

var scopes = new[] { "https://graph.microsoft.com/.default" };

GraphClient = new GraphServiceClient(clientSecretCredential, scopes);

var drive = await GraphClient                
    .Drives[dokumenteId]
    .Items
    .GetAsync(); //this line throws the exception

On execution the Code throws the following exception

The 'filter' query option must be provided.

is thrown. When looking into the documentation here, 'filter' was not mentioned. However, the example left me a bit confused

var result = await graphClient.Drives["{drive-id}"].Items["{driveItem-id}"].Children.GetAsync();

As it would mean, I need to pass the driveItem-id parameter, which, when parsing the root folder does not make sense.

How can I get a list of the items (folders and files) in a sharepoint library (i.e drive) that sits directly in the site?


Solution

  • It can't be done by one call. You need to start from the root drive item and get all children recursively.

    If a folder has more than 200 items, you need to use PageIterator to retrieve all items from the given folder.

    Method to get child items (not tested)

    public async Task<List<DriveItem>> GetChildItemsAsync(string driveId, string driveItemId, List<DriveItem> allDriveItems)
    {
        var allDriveItemChildren = new List<DriveItem>();
        var firstPage = await graphClient.Drives[driveId].Items[driveItemId].Children.GetAsync();
        var pageIterator = PageIterator<DriveItem, DriveItemCollectionResponse>.CreatePageIterator(graphClient, firstPage, driveItem =>
        {
            allDriveItemChildren.Add(driveItem);
            return true;
        });
    
        await pageIterator.IterateAsync();
    
        foreach (var item in allDriveItemChildren)
        {
            allDriveItems.Add(item);
            if (item.Folder != null && item.Folder.ChildCount > 0)
            {
                await GetChildItemsAsync(driveId, item.Id, allDriveItems);
            }
        }
        return allDriveItems;
    }
    

    Start with a root driveItem

    var allItems = new List<DriveItem>();
    var items = await GetChildItemsAsync("driveId", "root", allItems);