Search code examples
c#uwpmicrosoft-graph-apioffice365api

Getting a list of attached documents and downloading them into local storage using Microsoft Graph API in UWP


I am developing a UWP app using Microsoft Graph API. I am getting a list of meetings for the current day for a logged in user using the below API

https://graph.microsoft.com/v1.0/me/calendarView?startDateTime=2017-06-20T20:00:00.0000000&endDateTime=2017-06-21T10:00:00.0000000 

While creating the meeting , I had attached a document in the invite for the invited participants. The JSON Response received has "hasAttachments": true,. My requirement is to download the file that were send in the invite. I need to download those files in using my app and then attach them and send it to the participants. How can I do that?


Solution

  • My requirement is to download the file that were send in the invite.

    It seems like you are using List calendarView API to get the events. In that case you should be able get the event "id" property of the Event resource you want from the response, please check "id": "string (identifier)".

    After then, you can get all the attachments of this event by List attachments API, and get a special one attachment by Get attachment. You could get the binary contents of the attached file by contentBytes property which contains the base64-encoded contents of the file. If your attachment is fileAttachment resource type. For example, if the attachment is a .txt file, you can download it and save it in application local folder as follows:

    HttpClient client = new HttpClient();
    string token =await AuthenticationHelper.GetTokenForUserAsync();
    client.DefaultRequestHeaders.Add("Authorization", "Bearer "+token);
    HttpResponseMessage httpresponse = await client.GetAsync(new Uri("https://graph.microsoft.com/v1.0/me/events/{id}/attachments/{id}"));
    StorageFile downloadedfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("attachment.txt",CreationCollisionOption.ReplaceExisting); 
    JObject resObj = JObject.Parse(await httpresponse.Content.ReadAsStringAsync());
    string contentbyte = resObj["contentBytes"].ToString();
    await FileIO.WriteTextAsync(downloadedfile, Encoding.UTF8.GetString(Convert.FromBase64String(contentbyte)));
    

    Update: If the attachment is not a .txt, what actually needed is correctly transfer the base64-encode contents to file, for example:

    StorageFile downloadedfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("attachment.xlsx", CreationCollisionOption.ReplaceExisting);    
    string contentbyte = "contentbyte";
    byte[] filecontent = Convert.FromBase64String(contentbyte);
    await FileIO.WriteBytesAsync(downloadedfile, filecontent);