Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft Graph - Saving file attachments through C#?

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?

like image 321
user8608110 Avatar asked Jun 11 '26 19:06

user8608110


1 Answers

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);
        }
    }
}
like image 73
Tomas Paul Avatar answered Jun 14 '26 07:06

Tomas Paul