Search code examples
c#microsoft-graph-apimicrosoft-graph-sdksmicrosoft-graph-calendar

Is it possible to create calendar events with attachments?


I want to create a calendar event using Microsoft Graph and this is working but unfortunately, I'm not able to add attachments to the event. The event is created but without the attachments. No error is reported.

This is my code:

DateTimeTimeZone start = new DateTimeTimeZone
{
    TimeZone = TimeZoneInfo.Local.Id,
    DateTime = dateTimePicker1.Value.ToString("o"),
};

DateTimeTimeZone end = new DateTimeTimeZone
{
    TimeZone = TimeZoneInfo.Local.Id,
    DateTime = dateTimePicker2.Value.ToString("o"),
};

Location location = new Location
{
    DisplayName = "Thuis",
};

byte[] contentBytes = System.IO.File
    .ReadAllBytes(@"C:\test\sample.pdf");

var ev = new Event();

FileAttachment fa = new FileAttachment
{
    ODataType = "#microsoft.graph.fileAttachment",
    ContentBytes = contentBytes,
    ContentType = "application/pdf",
    Name = "sample.pdf",
    IsInline = false,
    Size = contentBytes.Length
};

ev.Attachments = new EventAttachmentsCollectionPage();
ev.Attachments.Add(fa);

ev.Start = start;
ev.End = end;
ev.IsAllDay = false;
ev.Location = location;
ev.Subject = textBox2.Text;

var response = await graphServiceClient
    .Users["[email protected]"]
    .Calendar
    .Events
    .Request()
    .AddAsync(ev);

Solution

  • It appears it still not supported to create an event along with attachments within a single request (a similar issue)

    As a workaround, an event without attachments could be created first and then attachments added into it (requires two requests to the server), for example:

    var ev = new Event
    {
        Start = start,
        End = end,
        IsAllDay = false,
        Location = location,
        Subject = subject
    };
    
    //1.create an event first 
    var evResp = await graphServiceClient.Users[userId].Calendar.Events.Request().AddAsync(ev);
    
    byte[] contentBytes = System.IO.File.ReadAllBytes(localPath);
    var attachmentName = System.IO.Path.GetFileName(localPath);
    var fa = new FileAttachment
    {
        ODataType = "#microsoft.graph.fileAttachment",
        ContentBytes = contentBytes,
        ContentType = MimeMapping.GetMimeMapping(attachmentName),
        Name = attachmentName,
        IsInline = false
    };
    
    //2. add attachments to event
    var faResp = await graphServiceClient.Users[userId].Calendar.Events[evResp.Id].Attachments.Request().AddAsync(fa);