c#outlook删除所有约会

时间:2010-09-27 19:18:24

标签: c# outlook

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();

}

这会删除约会,但一次只能删除,如果你继续重新运行它,它最终将全部删除...

有没有人知道发生了什么,我也尝试先排序,没有变化 -

谢谢!

在试验之后,向后循环做了 - 但不确定为什么

   Console.WriteLine(calendarFolder.Items.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();
    }

1 个答案:

答案 0 :(得分:1)

这就是向后循环修复它的原因。假设您在列表中有100个元素,每次迭代时都会检查for循环条件

i = 0 count = 99
i = 1 count = 98
      ...
i = 50 count = 49

for循环结束但元素50-99仍然存在,因此向后迭代不会导致错误。