How to: Add or Remove a Store

This example shows how to add and remove a store in a given profile.

This code sample shows how to add and remove a store in a specified profile, by calling the AddStoreEx method and the RemoveStore method respectively on the NameSpace object.

In Outlook, you can add or remove a PST store only programmatically. The following code sample adds a Unicode store and places the .pst file in the default location for user .pst files: Documents and Settings\<UserName>\Local Settings\Application Data\Microsoft\Outlook. The code sample uses Environment.SpecialFolder.LocalApplicationData to retrieve the path to the Application Data folder under the Local Settings folder. Once the store has been added, the code sample removes the store. Because the RemoveStore method requires a Folder object to remove the Store object, it enumerates the Stores collection to find the Store object that has just been added based on the FilePath property of the Store object.

RemoveStore only removes the store from the current profile. It does not delete the .pst file from the file system.

If you use Visual Studio to test this code example, you must first add a reference to the Microsoft Outlook 15.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 CreateUnicodePST()
{
    string path = Environment.GetFolderPath(
        Environment.SpecialFolder.LocalApplicationData)
        + @"\Microsoft\Outlook\MyUnicodeStore.pst";
    try
    {
        Application.Session.AddStoreEx(
            path, Outlook.OlStoreType.olStoreUnicode);
        Outlook.Stores stores = Application.Session.Stores;
        foreach (Outlook.Store store in stores)
        {
            if (store.FilePath == path)
            {
               Outlook.Folder folder =
                    store.GetRootFolder() as Outlook.Folder;
               // Remove the store
               Application.Session.RemoveStore(folder);
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}

Other resources

Community Additions

ADD
Show:
© 2014 Microsoft