Upload & download an excel file from Onedrive using C# razor page
Amit Patil
0
Reputation points
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.
Sign in to answer