Add or remove a store
This example shows how to add and remove a store in a given profile.
Example
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#.
Imports Outlook = Microsoft.Office.Interop.Outlook
using Outlook = Microsoft.Office.Interop.Outlook;
Private Sub CreateUnicodePST()
Dim path As String = Environment.GetFolderPath( _
Environment.SpecialFolder.LocalApplicationData) _
& "\Microsoft\Outlook\MyUnicodeStore.pst"
Try
Application.Session.AddStoreEx( _
path, Outlook.OlStoreType.olStoreUnicode)
Dim stores As Outlook.Stores = Application.Session.Stores
For Each store As Outlook.Store In stores
If store.FilePath = path Then
Dim folder As Outlook.Folder = _
CType(store.GetRootFolder(), Outlook.Folder)
' Remove the store
Application.Session.RemoveStore(folder)
End If
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
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);
}
}