【问题标题】:Download a file with the Microsoft Graph c# SDK by the file's full URL通过文件的完整 URL 下载带有 Microsoft Graph c# SDK 的文件
【发布时间】:2019-02-20 21:39:31
【问题描述】:
【问题讨论】:
标签:
c#
sharepoint
sdk
microsoft-graph-api
onedrive
【解决方案1】:
当谈到在 OneDrive API 中通过 Url 寻址资源时,shares endpoint 来救援。在这种情况下,通过完整 url 下载文件的流程可能包括以下步骤:
- 第一步是将 URL 转换为共享令牌(请参阅
下面的部分),为此我们使用
shares端点
- 生成共享令牌后,OneDrive API 请求
下载文件可以这样构造:
/shares/{shareIdOrEncodedSharingUrl}/driveitem/content
示例
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
如何将 URL 转换为共享令牌
以下 sn-p 演示如何将 URL 转换为共享令牌(改编自 here)
static string UrlToSharingToken(string inputUrl)
{
var base64Value = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(inputUrl));
return "u!" + base64Value.TrimEnd('=').Replace('/', '_').Replace('+', '-');
}