是否可以通过Microsoft Graph API在C#中保存文件附件?
我知道我可以获取附件的属性(https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/attachment_get) - 我们还能将它保存到某个位置吗?
答案 0 :(得分:1)
获得附件属性后,它们将包含有关附件的信息。
有three types个附件。
首先,检查属性“@odata.type
中的附件类型并相应地处理它们。
对于fileAttachment
类型,它们包含contentLocation
属性,即the URI of the attachment contents。
您可以从URI下载附件。
答案 1 :(得分:1)
一旦收到特定的Microsoft Graph消息,您可以例如将其作为参数传递给方法。然后,您需要发出另一个请求,以通过消息ID获取附件,遍历附件并将其强制转换为FileAttachment
,以访问ContentBytes
属性,最后将此字节数组保存到文件中。
private static async Task SaveAttachments(Message message)
{
var attachments =
await _client.Me.MailFolders.Inbox.Messages[message.Id].Attachments.Request().GetAsync();
foreach (var attachment in attachments.CurrentPage)
{
if (attachment.GetType() == typeof(FileAttachment))
{
var item = (FileAttachment)attachment; // Cast from Attachment
var folder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var filePath = Path.Combine(folder, item.Name);
System.IO.File.WriteAllBytes(filePath, item.ContentBytes);
}
}
}