How to retrieve all items stored in a drive with the Graph .NET SDK

Drive items

Sometimes you need to get all files stored in a personal's OneDrive or in document library in SharePoint. The Microsoft Graph API expose several endpoints for that purpose.

The endpoint GET v1.0/drives/{driveId} provides the access to the properties and relationships of a Drive resource. A Drive is the top-level container for a file system, such as OneDrive or SharePoint document libraries.

Drive resource has the relationship to a collection of driveItems called items. The items collection works more like a dictionary, so you can't simply call GET v1.0/drive/{driveId}/items to get all items. It will throw an error:

{
    "error": {
        "code": "invalidRequest",
        "message": "The 'filter' query option must be provided."
    }
}

The driveItem resource represents a file, folder, or other item stored in a drive. What's important, the driveItem has the relationship children to a collection of child items.

Retreive all drive items

To retrieve all items, you need to start from the root folder of the drive and recursively retrieve all child items.

In fact, to retrieve all items, you can call only one endpoint

GET v1.0/drive/{driveId}/items/{driveItemId}/children

Be aware that the endpoint returns by default 200 items. If a folder has more than 200 items, you need to implement paging to retrieve all items in the folder.

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();
    // if folder has more than 200 items, we need to use PageIterator to retrieve all items
    var pageIterator = PageIterator<DriveItem, DriveItemCollectionResponse>.CreatePageIterator(graphClient, firstPage, driveItem =>
    {
        allDriveItemChildren.Add(driveItem);
        return true;
    });

    await pageIterator.IterateAsync();

    // recursion: retrieve driveItem for each child
    foreach (var item in allDriveItemChildren)
    {
        allDriveItems.Add(item);
        // only folder has child
        if (item.Folder != null && item.Folder.ChildCount > 0)
        {
            await GetChildItemsAsync(driveId, item.Id, allDriveItems);
        }
    }
    return allDriveItems;
}

The main call

var items = new List<DriveItem>();
var allDriveItems = await GetChildItemsAsync(driveId, "root", items);
1
Buy Me a Coffee at ko-fi.com
An error has occurred. This application may no longer respond until reloaded. Reload x