Use the OneDrive API to enumerate more than 200 items in a folder

Page update date :
Page creation date :

Operating environment

Visual Studio
  • Visual Studio 2022
.NET
  • .NET 8
Microsoft Authentication API
  • 2.0 OAuth 2
Microsoft OneDrive API
  • 1.0
Microsoft.Graph
  • 5.68.0
Types of Microsoft accounts
  • Work or school account

Prerequisites

Visual Studio
  • One of the versions
.NET
  • One of the versions
Microsoft Authentication API
  • 2.0 OAuth 2
Microsoft OneDrive API
  • 1.0
Microsoft.Graph
  • 5.XX
Types of Microsoft accounts
  • Work or school account

The maximum number of items that can be retrieved at one time

When retrieving the contents of a folder with the OneDrive API, the maximum number that can be retrieved at one time is 200. This figure can also be found on the official website below.

This is true even if you hit the URL directly, but Microsoft.Graph also if you use the library. The following code, which was mentioned in the previous tips, only retrieves up to 200 results. No errors will occur,DriveItemCollectionResponse.OdataNextLink but you can check whether there are more than 201 items by checking whether the value of the property is set.

// フォルダ内アイテム一覧取得
var folderChildren = await graphClient.Drives[drive.Id].Items[folderItem.Id].Children.GetAsync();
if (folderChildren == null || folderChildren.Value == null)
{
  Console.WriteLine("フォルダの一覧を取得できませんでした。");
  return;
}
foreach (var item in folderChildren.Value)
{
  Console.WriteLine($"Type={(item.File != null ? "File" : "Folder")}, Id={item.Id}, Name={item.Name}, Size={item.Size}");
}

If you want to get it by HTTP request, you @odata.nextLink need to access the URL of one by one to get it. Microsoft.Graph If you're using the library, there's an easier way to get all more than 200 items. PageIterator There is a class called , so all you have to do is use it. Use it as follows:

// フォルダ内アイテム一覧取得
var folderChildren = await graphClient.Drives[drive.Id].Items[folderItem.Id].Children.GetAsync();
if (folderChildren == null || folderChildren.Value == null)
{
  Console.WriteLine("フォルダの一覧を取得できませんでした。");
  return;
}

var pageIterator = PageIterator<DriveItem, DriveItemCollectionResponse>.CreatePageIterator(
      graphClient,
      folderChildren,
      (item) =>
      {
        Console.WriteLine($"Type={(item.File != null ? "File" : "Folder")}, Id={item.Id}, Name={item.Name}, Size={item.Size}");
        return true;  // false を返すまで次のアイテムを列挙します
      });
await pageIterator.IterateAsync();

Once you get the folder item list response (DriveItemCollectionResponse) PageIterator.CreatePageIterator Specify it as the second argument of the method. The third argument is a callback, which is called on an item-by-item basis, so if you list it, you should be able to get all the items.

PageIterator.CreatePageIterator By the way, is just generating an iteration, so we need to call the method at the end PageIterator.IterateAsync .