Outlook: Programmatically select a Folder

The Microsoft Object Model has a method that allows you to select a folder inside the Outlook data structure.
"PickFolder" is the name of it and it is accessible via the NameSpace Object, that means the Session property of the Application object.
As a result you will get an instance of the selected Outlook-Folder or null if nothing was selected.
You can use the DefaultItemType property of the folder to check if the folder contains the correct item types.

Below you can see a sample implementation – only contact folders are allowed by this method:

///<summary>
/// This method displays the PickFolder Dialog and checks if an Contact folder has been selected
///</summary>
private Outlook.MAPIFolder SelectOutlookContactFolder(Outlook.NameSpace session) {
 
    bool result = false;
    string messageBoxText = string.Empty;
 
    // The Outlook COM Object used
    Outlook.MAPIFolder folder;
    try {
 
        // This will display a Dialog to choose an Outlook Folder
        folder = session.PickFolder();
 
        // Check if we have a Folder that contains ContactItems
        if (folder != null && folder.DefaultItemType == Outlook.OlItemType.olContactItem) {
            result = true;
 
        } else {
 
            // Notify the User it doesn't make sense
            messageBoxText = "Please select a valid Contact folder";
 
        }
    } catch (System.Exception ex) {
 
        // In case an error occured noitify the User
        messageBoxText = string.Format("There was an error accessing the Outlook application.\n{0}", ex.Message);
 
    }
 
    if (!result) {
        // Wrong Folder selected or Error
        folder = null;
        MessageBox.Show(messageBoxText, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
    return folder;
} 

Happy coding…

Add a Comment