I am having some issues getting all the appointments from specific month. Problem is with appointments that has been scheduled with recurring setting. Is there some way to get all appointments present in outlook calendar recurring and not recurring?
The best so far I was able to achieve is to check for is appointment.IsRecurring
and if true I can get some parameters from recurrencePattern
. However it seems to work only for appointments that has been set in this specific month with recurring parameter. If appointment with recurrence has been set earlier, then current code does not seem to work.
Is there some way to get just all the appointments from specific month?
private void GetAllItems(DateTime startDate, DateTime endDate)
{
Outlook.Application outlookApp = new Outlook.Application();
Outlook.NameSpace outlookNamespace = outlookApp.GetNamespace("MAPI");
Outlook.MAPIFolder calendarFolder = outlookNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
Outlook.Items calendarItems = calendarFolder.Items;
string restriction = $"[Start] >= '{startDate.ToShortDateString()}' AND [Start] <= '{endDate.ToShortDateString()}'";
Outlook.Items filteredItems = calendarItems.Restrict(restriction);
foreach (Outlook.AppointmentItem appointment in filteredItems)
{
DataModel dataModel = new DataModel
{
Subject = appointment.Subject,
};
this.Data.Add(dataModel);
if (appointment.IsRecurring)
{
Outlook.RecurrencePattern recurrencePattern = appointment.GetRecurrencePattern();
DataModel recurringDataModel = new DataModel
{
Subject = appointment.Subject,
};
this.Data.Add(recurringDataModel);
}
}
}
You are almost there - you need to set the Items.IncludeRecurrences
property to true and call Items.Sort
on the Start
property to tell Items.Restrict
to expand the recurrences. See https://learn.microsoft.com/en-us/office/vba/api/outlook.items.includerecurrences for more details and an example
Outlook.Items calendarItems = calendarFolder.Items;
calendarItems.Sort("[Start]");
calendarItems.IncludeRecurrences = true;
string restriction = $"[Start] >= '{startDate.ToShortDateString()}' AND [Start] <= '{endDate.ToShortDateString()}'";
Outlook.Items filteredItems = calendarItems.Restrict(restriction);