简体   繁体   中英

VSTO: Iterating through Outlook inbox raises error when non-mail items appears

I have some code in Visual Studio (VSTO + VB.Net) that shall iterate through all items in my Outlook Inbox. The code works fine until there are other items in my Inbox, such as appointments etc.

The code below is simplified and iterates through all items in a sorted list. The problem occurs when FolderItem (of type MailItem) is assigned with an item that is of other types, eg MeetingItemClass. An exception is raised.

I understand why... But I need a solution on how to find a workaround. I want to process ALL items, even meeting items.

Dim InboxFolder As Outlook.MAPIFolder
Dim FolderItem As Outlook.MailItem
Dim FolderItems As Outlook.Items
Dim ItemNo As Integer

*** removed code that finds the inbox object 'InboxFolder' ***

ItemNo = 1
FolderItems = InboxFolder.Items
FolderItems.Sort("[ReceivedTime]", True)

Do While ItemNo <= FolderItems.Count
    FolderItem = FolderItems(ItemNo)

    *** Do some operations on each inbox-object here ***

    ItemNo = ItemNo + 1
Loop

A possiblility is to define FolderItem As Object and then...

  • ...check the type before assigning it to a variable of the specific type

AND

  • ...cast it to the specific type in your while loop if necessary

Something like this (not tested):

If TypeOf FolderItem Is MailItem Then
   Dim mailItm As MailItem = DirectCast(FolderItem, MailItem)
   'Do something
ElseIf TypeOf FolderItem Is MeetingItem Then
   Dim meetItm As MeetingItem = DirectCast(FolderItem, MeetingItem)
   'Do something
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM