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
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:
shares
endpoint/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('+', '-');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With