How to: Filter and Efficiently Enumerate Items in a Folder

This example shows how to use the Table object to filter for items in the Inbox that have attachments, and efficiently enumerate such items, displaying selected properties for each item.

The code sample specifies the property PR_HASATTACH with the MAPI namespace, and uses the property to create the initial filter in the GetTable method on the Inbox. A Table object for an item type has default columns representing certain properties of that item type. To customize the columns, this example first calls the RemoveAll method on the Columns collection of that Table, and then calls the Add method on the Columns collection to add the EntryID, Subject, and ReceivedTime properties using the built-in property names, with the ReceivedTime column storing values in local date-time representation. The example then calls Columns.Add one more time to add the ReceiveTime property specifying its MAPI namespace so that this column will store the value as a Universal Coordinated Time (UTC) date-time value. Finally, the example enumerates each item in the Table, displaying the value of each of the four properties specified as the table columns.

If you use Microsoft Visual Studio to test this code example, you must first add a reference to the Microsoft Outlook 14.0 Object Library component and specify the Outlook variable when you import the Microsoft.Office.Interop.Outlook namespace. The Imports or using statement must not occur directly before the functions in the code example but must be added before the public Class declaration. The following lines of code show how to do the import and assignment in Visual Basic and C#.

using Outlook = Microsoft.Office.Interop.Outlook;
private void DemoTableColumns()
    const string PR_HAS_ATTACH =
    // Obtain Inbox
    Outlook.Folder folder =
        as Outlook.Folder;
    // Create filter
    string filter = "@SQL=" + "\""
        + PR_HAS_ATTACH + "\"" + " = 1";
    Outlook.Table table =
    // Remove default columns
    // Add using built-in name
    table.Sort("ReceivedTime", Outlook.OlSortOrder.olDescending);
    // Add using namespace
    // Date received
    while (!table.EndOfTable)
        Outlook.Row nextRow = table.GetNextRow();
        StringBuilder sb = new StringBuilder();
        // Reference column by name 
        sb.AppendLine("Received (Local): "
            + nextRow["ReceivedTime"]);
        // Reference column by index
        sb.AppendLine("Received (UTC): " + nextRow[4]);

Other Resources