I can use the following VB code to open an Outlook .pst file
Dim olApp As Application = New Application()
Dim oNS As [NameSpace] = olApp.GetNamespace("mapi")
Dim sStore As String = "[path to .pst file]"
oNS.Session.AddStore(sStore)
' do something - read messages, whatever
'oNS.Session.RemoveStore(sStore)
olApp.Close
olApp.Dispose
NB: sStore is a path to an archived .pst file and is not open in Outlook itself.
This works... however, before running it I close Outlook (normally running on my PC). Then, after running this code, on re-opening Outlook I see that the .pst file has been added/opened and is there to be viewed in Outlook.
What I want to do is close it in the code so that it is not in Outlook when I re-open that. I imagined that the commented out line 'oNS.Session.RemoveStore(sStore) would do this, but it doesn't - and in fact Visual Studio's intellisense flags a potential error with it telling me that the expected argument for RemoveStore is an Outlook folder, not a string. (For AddStore it's just an Object). Seems strange to me (ignoramus that I be) - why is it a folder? Anyway, grateful for any clues about removing the entire "store".
(I've used VB code here, but am OK with C#)
- update -
To clarify: my Outlook has one .PST file (for my IMAP/POP3 accounts) and two Exchange accounts. With the code I am on about I want to temporarily open another .PST file.
Following Dimitri's comment below, I tried the line
oNS.Session.RemoveStore(CType(olApp.Session.Stores(olApp.Session.Stores.Count - 1).GetRootFolder(), Folder))
What Dimitri suggests can't be done, as sStore is just a String, so I tried using the root folder of the last added olApp.Session "store".
This produced unexpected results, and not even consistent ones. (On one occasion my default .pst files was removed!) SO I tried logging, just to see
Dim r As Integer
Dim sb As New StringBuilder
For r = 0 To olApp.Session.Stores.Count - 1
sb.AppendLine(olApp.Session.Stores(r).FilePath)
Next
and on different runs I get the paths listed in a different order! And, for some reason, the file path to my just last added store doesn't even get listed, except there is a blank line added. ??
So... I guess what I need is a way to know what "r" in the iteration loop corresponds to the .pst file I want to remove. Maybe just look for a blank FilePath, but this seems rather crude and prone to unexpected consequences - there must a proper way to do this.
Your loop is wrong - all OOM collections are 1 based, not 0. It must be