c# outlook delete all appointments
Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MAPIFolder calendarFolder = outlookApp.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);
Console.WriteLine(calendarFolder.Items.Count);
foreach (Microsoft.Office.Interop.Outlook.AppointmentItem c in calendarFolder.Items)
{
Console.WriteLine(c.Subject.ToString() + " " + c.Start.ToString() + " deleted");
c.Delete();
}
This deletes appointments, but only chucks at a time,if you keep re-running this it eventually deletes them all...
does anyone know what is going on, I also tried to Sort it first, no change--
Thanks!!
after experimenting, looping backwards did it-- not really sure why however
Console.WriteLine(calendarFolder.Item开发者_如何学运维s.Count);
Microsoft.Office.Interop.Outlook.Items calendarItems = calendarFolder.Items;
//Microsoft.Office.Interop.Outlook.AppointmentItem app = calendarItems as Microsoft.Office.Interop.Outlook.AppointmentItem;
//for (int i = 1; i <= calendarFolder.Items.Count; i++)
for (int i = calendarFolder.Items.Count; i > 0; i--)
{
calendarFolder.Items[i].Delete();
//app = calendarFolder.Items[i];
Console.WriteLine(i);
//app.Delete();
}
This is the reason that looping backwards fixed it. Let's say you had 100 elements in the list, you check the for loop condition each time you iterate
i = 0 count = 99
i = 1 count = 98
...
i = 50 count = 49
The for
loop ends but elements 50-99 would still exist hence why iterating backwards does not cause the bug.
精彩评论