Search code examples
c#asp.net-coremicrosoft-graph-apiazure-identityclientcredential

Connect to OneDrive using Microsoft Graph and C# not working


I was trying to create a very simple app to connect to my OneDrive and receive a list of the various files that I have hosted on OneDrive.

This is the code:

string clientId = "My client Id";
string clientSecret = "The secret id value";
string tenantId = "My tenant id";
      
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential);

var driveItems = await graphClient.Me.Drive.Root.Children.Request().GetAsync();

// Display the names of all items in the list
foreach (var item in driveItems)
{
    Console.WriteLine(item.Name);
}

The problem is that apparently graphClient.Me.Drive does not contain a Root definition (at least that's what Visual Studio tells me).

I am using Microsoft.Graph v5.11 and Azure.Identity v1.9


Solution

  • You are now using Microsoft.Graph v5.11 which is different from V4.x and in V5 there's no .Request().

    In the meantime, you are using client credential flow new ClientSecretCredential, so you can't use .Me but have to use .Users["your_user_id"]. Because you don't sign in first, so you have to give a user id manually. By the way, since you are using client credential flow, you have to set the scope as var scopes = new[] { "https://graph.microsoft.com/.default" };. This requires you to consent application type of api permission:

    enter image description here enter image description here

    Then you code based on V5.11 should be like:

    var scopes = new[] { "https://graph.microsoft.com/.default" };
    var tenantId = "tenantId ";
    var clientId = "clientId ";
    var clientSecret = "clientSecret";
    var clientSecretCredential = new ClientSecretCredential(
                                tenantId, clientId, clientSecret);
    var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
    var userDriveId = await graphClient.Users["yourUserId"].Drive.GetAsync();
    var driveItems = await graphClient.Drives["userDriveId"].Items["Root"].Children.GetAsync();
    

    Related link: https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/feature/5.0/docs/upgrade-to-v5.md#drive-item-paths

    enter image description here