We have multiple SharePoint sites, and our application is registered on the domain. Currently, we are trying to fetch documents from SharePoint using a client ID and secret, but we are encountering issues. We have used the GraphClient but receive empty objects for the root, drives, and item lists. We have also ensured that all permissions are granted at the application level. Here is the code snippet : (code developed in .net 8 and we have used latest Microsoft.Identity.Client Nuget package)
public async Task<string> GetAccessTokenAsync()
{
string[] scopes = { "https://graph.microsoft.com/.default" };
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
// Retrieve the files from the "My Files" folder (OneDrive root)
var document = await graphClient.Users["[email protected]"].GetAsync();
var driveItems = await graphClient.Sites["XXXX-my.sharepoint.com"].GetAsync();
foreach (var items in document.Drive.Items)
{
Console.WriteLine(items.Name);
}
}
How can we retrieve all "My Files" documents using Microsoft Graph?
2
Answers
In OneDrive My files in my environment is like below:
Use the below code to retrieve all "My Files" using Microsoft Graph:
I got the response successfully like below:
var url = $"https://graph.microsoft.com/v1.0/users/{userId}/drive/root/children";
directy if you do not want to pass DriveID.Make sure the Microsoft Entra ID application is granted with
Files.Read.All
application type API permission.To access user’s drive, you need to call
graphClient.Users["[email protected]"].Drive.GetAsync()
, your current callgraphClient.Users["[email protected]"].GetAsync()
returns basic info about the user, but without a drive.When iterating drive’s items, you should handle paging and probably iterate through all subfolders.
If you still prefer using the Graph SDK v5, you can use this helper method to retrieve all files from user’s or SharePoint site’s drive
Calling the helper method from main code