Skip to content

Instantly share code, notes, and snippets.

@smourier
Created February 19, 2020 10:56
Show Gist options
  • Save smourier/e987c17d8e2906257f8ab0502c12a768 to your computer and use it in GitHub Desktop.
Save smourier/e987c17d8e2906257f8ab0502c12a768 to your computer and use it in GitHub Desktop.
List OneDrive root files
using System;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.Identity.Client;
namespace ConsoleApp18
{
// needs Microsoft.Graph and Microsoft.Graph.Auth nuget packages
class Program
{
static void Main()
{
var prov = new DelegateAuthenticationProvider(async (request) =>
{
var res = await GetTokenAsync();
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", res.AccessToken);
});
var client = new GraphServiceClient(prov);
var items = client.Me.Drive.Root.Children.Request().GetAsync().Result;
foreach (var item in items)
{
Console.WriteLine(item.Name + " id:" + item.Id);
}
}
private static async Task<AuthenticationResult> GetTokenAsync()
{
var app = PublicClientApplicationBuilder
.Create("7c9efca5-2406-48b9-a1dc-e9bcb7d12446") // client id
.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
.Build();
var scopes = new[] { "User.Read", "Files.Read.All" }; // + drive scope
var accounts = await app.GetAccountsAsync();
AuthenticationResult result;
try
{
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
}
catch (MsalUiRequiredException)
{
result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment