How to: Assign Categories to an Item

This example shows how to assign categories to an item by using its Categories property.

Programming Applications for Office Outlook 2007

The following code example is an excerpt from Programming Applications for Microsoft Office Outlook 2007, from Microsoft Press (ISBN 9780735622494, copyright Microsoft Press 2007, all rights reserved).

Buy this book

Sample chapters

To assign categories to an item, use the particular item's Categories property. This code sample makes use of the OutlookItem helper class, defined in How to: Create a Helper Class to Access Common Outlook Item Members, to conveniently call the OutlookItem.Categories property without having to first cast the item. The Categories property gets or sets categories that are represented by a comma-delimited string that can contain a maximum of 255 characters. The commas and spaces are used to separate the category values. Assigning a category that is not in the Categories collection of the NameSpace object will result in the category not displaying a color.

In the following code example, AssignCategories creates a restriction for items that contain “ISV” in the subject by first using a DAV Searching and Locating (DASL) query to filter items in the Inbox that contain “ISV” in the subject. AssignCategories then iterates through the filtered items by using the OutlookItem class and, if the string returned by item.Categories is not a null reference or was already assigned to the ISV, the ISV category is assigned to the item.

using Outlook = Microsoft.Office.Interop.Outlook;
private void AssignCategories()
{
    string filter = "@SQL=" + "\"" + "urn:schemas:httpmail:subject"
        + "\"" + " ci_phrasematch 'ISV'";
    Outlook.Items items =
        Application.Session.GetDefaultFolder(
        Outlook.OlDefaultFolders.olFolderInbox).Items.Restrict(filter);
    for (int i = 1; i <= items.Count; i++)
    {
        OutlookItem item = new OutlookItem(items[i]);
        string existingCategories = item.Categories;
        if (String.IsNullOrEmpty(existingCategories))
        {
            item.Categories = "ISV";
        }
        else
        {
            if (item.Categories.Contains("ISV") == false)
            {
                item.Categories = existingCategories + ", ISV";
            }
        }
        item.Save();
    }
}

Other resources

Show:
© 2014 Microsoft