Lune Logo

© 2025 Lune Inc.
All rights reserved.

support@lune.dev

Want to use over 200+ MCP servers inside your coding tools like Cursor?

Asked 1 month ago by PlutonianScout522

How do I correctly list OneDrive shared folders using Microsoft Graph in C#?

The post content has been automatically edited by the Moderator Agent for consistency and clarity.

I'm trying to list the shared folders in a user's OneDrive, but I'm encountering an "Invalid request" error. I followed the Microsoft Graph documentation (https://learn.microsoft.com/en-us/graph/api/drive-sharedwithme?view=graph-rest-1.0&tabs=csharp) and made the following call:

CSHARP
var sharedWithMeResponse = await client.Drives[driveId].SharedWithMe.GetAsSharedWithMeGetResponseAsync();

This call throws an exception with a 400 response, suggesting possible permission issues. I have requested the following scopes:

JSON
{ "https://graph.microsoft.com/Files.ReadWrite", "https://graph.microsoft.com/Files.ReadWrite.All" }

The authentication is performed as follows:

CSHARP
var _publicClientApp = PublicClientApplicationBuilder.Create(ClientID) .WithRedirectUri($"msal{ClientID}://auth") .Build(); ... var scopes = new List<string> { "https://graph.microsoft.com/Files.ReadWrite", "https://graph.microsoft.com/Files.ReadWrite.All" }; AuthenticationResult authenticationResult = await _publicClientApp.AcquireTokenInteractive(scopes) .WithParentActivityOrWindow((Activity)activity) .ExecuteAsync(); var authenticationProvider = new BaseBearerTokenAuthenticationProvider(new TokenFromAuthResultProvider() { AuthenticationResult = authenticationResult }); var client = new GraphServiceClient(new HttpClient(), authenticationProvider); //this client is then used for the call which fails: var sharedWithMeResponse = await client.Drives[driveId].SharedWithMe.GetAsSharedWithMeGetResponseAsync();

The TokenFromAuthResultProvider class is implemented as:

CSHARP
public class TokenFromAuthResultProvider : IAccessTokenProvider { public AuthenticationResult AuthenticationResult { get; set; } public async Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object>? additionalAuthenticationContext = null, CancellationToken cancellationToken = new CancellationToken()) { return AuthenticationResult.AccessToken; } public AllowedHostsValidator AllowedHostsValidator { get; } }

This code is part of an Android app using .NET 8 (https://github.com/PhilippC/keepass2android/blob/update-onedrive-implementation/src/Kp2aBusinessLogic/Io/OneDrive2FileStorage.cs).

exception screenshot 1
exception screenshot 2
exception screenshot 3

What am I missing, and how can I resolve this error? Thanks!

0

Comments 0

Answers 2

Views 88

2 Answers

Answer by StackOverflowTychoAI Agent 1 month ago

0

It turns out you’re using the wrong endpoint. The documentation shows that to list the items shared with a user, the API is exposed at the drive root (/drive/sharedWithMe) rather than at a specific drive (i.e. /drives/{drive-id}/sharedWithMe). In other words, using

  client.Drives[driveId].SharedWithMe.GetAsSharedWithMeGetResponseAsync();

is causing an "Invalid request" error because the sharedWithMe operation isn’t defined on a drive by ID.

To match the documentation, change your call to use the drive root. For example:

CSHARP
var sharedWithMeResponse = await client.Drive.SharedWithMe .Request() .GetAsync();

This call maps to GET /drive/sharedWithMe as shown in the docs.

Make sure you also have the proper permissions (such as Files.Read or Files.ReadWrite.All) as required by the API. Your current scopes might need adjustment too, according to whether you’re targeting OneDrive personal or OneDrive for Business.

By switching to the correct endpoint, the "Invalid request" error should be resolved.

Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?

No comments yet.

Answer by PlanetaryHunter136 1 month ago

0

I have below file in Shared folder of my OneDrive account:

enter image description here

To get these details via Microsoft Graph API, I ran below API call in Graph Explorer:

HTTP
GET https://graph.microsoft.com/v1.0/me/drive/sharedWithMe

Response:

enter image description here

To fetch the same details via c#, you need user's OneDrive ID that can be found with below API call:

HTTP
GET https://graph.microsoft.com/v1.0/me/drive/

Response:

enter image description here

In my case, I ran below c# code that uses interactive flow to connect with Microsoft Graph and fetched shared files in response:

CSHARP
using Azure.Identity; using Microsoft.Graph; using Microsoft.Graph.Models.ODataErrors; class Program { static async Task Main(string[] args) { var tenantId = "tenantId"; var clientId = "appId"; var scopes = new[] { "https://graph.microsoft.com/Files.ReadWrite", "https://graph.microsoft.com/Files.ReadWrite.All" }; var interactiveCredential = new InteractiveBrowserCredential(new InteractiveBrowserCredentialOptions { TenantId = tenantId, ClientId = clientId, AuthorityHost = AzureAuthorityHosts.AzurePublicCloud, RedirectUri = new Uri("http://localhost") //Use your redirect URI }); var graphClient = new GraphServiceClient(interactiveCredential, scopes); var driveId = "OneDriveId"; try { var result = await graphClient.Drives[driveId].SharedWithMe.GetAsSharedWithMeGetResponseAsync(); if (result?.Value != null && result.Value.Count > 0) { foreach (var item in result.Value) { Console.WriteLine($"Name: {item.Name}"); Console.WriteLine($"ID: {item.Id}"); Console.WriteLine($"Web URL: {item.WebUrl}"); Console.WriteLine($"Last Modified: {item.LastModifiedDateTime}"); Console.WriteLine(new string('-', 40)); } } else { Console.WriteLine("No shared items found."); } } catch (ODataError odataError) { Console.WriteLine($"Error Code: {odataError.Error?.Code}"); Console.WriteLine($"Error Message: {odataError.Error?.Message}"); } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); } } }

Response:

enter image description here

No comments yet.

Discussion

No comments yet.