Hi Naresh Goty, Thanks for reaching out. You can use the following code to recursively read all the items in a drive using graph api.
private async Task<List<DriveItem>> GetAllFilesFromOneDriveSubFolderAsync(GraphServiceClient graphClient, DriveItem oneDriveSubFolder)
{
var subDriveItems = new List<DriveItem>();
var subDriveItemFiles = new List<DriveItem>();
//Fetching out all the files and sub folders inside the subfolder
IDriveItemChildrenCollectionPage items = await graphClient.Drives[oneDriveSubFolder.ParentReference.DriveId]
.Items[oneDriveSubFolder.Id].Children
.Request()
.GetAsync();
subDriveItems.AddRange(items.CurrentPage);
//Checking if there are more than one pages, if so fetch out from all the subsequent pages
var next = items.NextPageRequest;
while (next != null)
{
items = await next.GetAsync();
subDriveItems.AddRange(items.CurrentPage);
next = items.NextPageRequest;
}
//In case there is still sub folder then repeating the process to fetch out files
foreach (DriveItem driveItem in subDriveItems)
{
if (driveItem.Folder != null)
{
subDriveItemFiles.AddRange(await GetAllFilesFromOneDriveSubFolderAsync(graphClient, driveItem));
}
else if (driveItem.File != null)
{
subDriveItemFiles.Add(driveItem);
}
}
return subDriveItemFiles;
}
public async Task<List<DriveItem>> GetUsersOneDriveRootFilesAsync(GraphServiceClient graphClient, string userId, string driveId)
{
var driveItems = new List<DriveItem>();
var driveItemFiles = new List<DriveItem>();
//Fetching out all the files and sub folders inside the root folder of users one drive
var items = await graphClient.Drives[driveId]
.Root.ItemWithPath("/Templates")
.Children
.Request()
.WithMaxRetry(3, 3)
.GetAsync();
driveItems.AddRange(items.CurrentPage);
//Checking if there are more than one pages, if so fetch out from all the subsequent pages
var next = items.NextPageRequest;
while (next != null)
{
items = await next.GetAsync();
driveItems.AddRange(items.CurrentPage);
next = items.NextPageRequest;
}
// In case there is still sub folder then fetching out the files from the folder.
foreach (DriveItem driveItem in driveItems)
{
if (driveItem.Folder != null)
{
driveItemFiles.AddRange(await GetAllFilesFromOneDriveSubFolderAsync(graphClient, driveItem));
}
else if (driveItem.File != null)
{
driveItemFiles.Add(driveItem);
}
}
return driveItemFiles;
}
If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".