Upload & download an excel file from Onedrive using C# razor page

Amit Patil 0 Reputation points
2024-03-28T11:24:47.2+00:00

I am trying to upload & download an excel file to Onedrive using c# razor pages and have tried following code snippets,

// Install Microsoft.Graph SDK 
// Install Microsoft.Identity.Client (MSAL) SDK 
// Authentication 
var confidentialClientApplication = ConfidentialClientApplicationBuilder .
Create("{clientId}") .WithClientSecret("{clientSecret}") .
WithAuthority(new Uri("https://login.microsoftonline.com/{tenantId}")) .Build(); 
var authResult = await confidentialClientApplication.AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" }).ExecuteAsync(); 
// Access OneDrive API 
var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); 
return Task.FromResult(0); })); 
// Upload File 
using (var stream = new FileStream("path_to_file", FileMode.Open)) 
{ await graphServiceClient.Me.Drive.Root.ItemWithPath("file_name.xlsx").Content.Request().PutAsync<DriveItem>(stream); } 
// Download File 
var downloadedFile = await graphServiceClient.Me.Drive.Root.ItemWithPath("file_name.xlsx").Content.Request().GetAsync();

I am using Visual Studio 2022 Professional with Dotnet Framework 8.0

But has encountered the errors like Root is not available under Drive

I have managed to get the authentication token using above code snippet, but unable to upload/download the file.

Please help.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,142 questions
OneDrive
OneDrive
A Microsoft file hosting and synchronization service.
801 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,207 questions
OneDrive Management
OneDrive Management
OneDrive: A Microsoft file hosting and synchronization service.Management: The act or process of organizing, handling, directing or controlling something.
1,116 questions
{count} votes