Microsoft Graph - Saving file attachments through C#?

最后都变了- 提交于 2020-05-15 18:13:05

问题


Is it possible to save file attachments in C# through Microsoft Graph API?

I know I can get the properties of the attachment (https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/attachment_get) - can we also save it to a certain location?


回答1:


When you get the attachment properties, they will contain information about the attachment.

There are three types of attachments.

First, check the attachment type in the properties' @odata.type and handle them correspondingly.

For fileAttachment types, they contain a contentLocation attribute, which is the URI of the attachment contents.

You can download the attachment from the URI.




回答2:


Once you have particular Microsoft Graph message, you can e.g. pass it to a method as parameter. Then you need to make another request to get attachments by message Id, iterate through attachments and cast it to FileAttachment to get access to the ContentBytes property and finally save this byte array to the file.

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);
        }
    }
}


来源:https://stackoverflow.com/questions/49147472/microsoft-graph-saving-file-attachments-through-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!