Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file with the Microsoft Graph c# SDK by the file's full URL

I have a list of fully qualified URLs and I am looking to download the files out of SharePoint and business OneDrive folders. The URLs are as follows: https://tenant-my.sharepoint.com/personal/bob_smith_tenant_onmicrosoft_com/Documents/Microsoft Teams Chat Files/file.csv

https://tenant.sharepoint.com/sites/Development/Shared%20Documents/General/file2.pdf

I am not seeing a way with the Graph SDK to directly download files. I have successfully download the SharePoint file with CSOM but I'd prefer to use Graph so it can handle both file types if possible. Does anyone know if this is possible? Thanks in advance

like image 324
Kevin Tracey Avatar asked Mar 04 '23 11:03

Kevin Tracey


1 Answers

When it comes to addressing resource by Url in OneDrive API, shares endpoint comes to the rescue. In that case the flow for downloading a file by full url could consists of the following steps:

  • first step would be to transform the URL into a sharing token (see below section), for that matter we utilize shares endpoint
  • once the sharing token is generated, the OneDrive API request to download a file could be constructed like this: /shares/{shareIdOrEncodedSharingUrl}/driveitem/content

Example

const string fileFullUrl = "https://contoso-my.sharepoint.com/personal/jdoe_contoso_onmicrosoft_com/documents/sample.docx";


var sharedItemId = UrlToSharingToken(fileFullUrl);
var requestUrl = $"{graphClient.BaseUrl}/shares/{sharedItemId}/driveitem/content";
var message = new HttpRequestMessage(HttpMethod.Get, requestUrl);
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(message);
var response = await graphClient.HttpProvider.SendAsync(message);
var bytesContent = await response.Content.ReadAsByteArrayAsync();

System.IO.File.WriteAllBytes("sample.docx", bytesContent); //save into local file

How to transform the URL into a sharing token

The following snippet demonstrates how to transform the URL into a sharing token (adapted from here)

static string UrlToSharingToken(string inputUrl)
{
   var base64Value = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(inputUrl));
   return "u!" + base64Value.TrimEnd('=').Replace('/', '_').Replace('+', '-');
}
like image 63
Vadim Gremyachev Avatar answered Mar 10 '23 10:03

Vadim Gremyachev