How can I create an Outlook PST file using .Net?
I'm writing an app that will manipulate Outlook data. I want to make a backup of that data first and am hoping I could just loop through the contact/calendar items, etc and write them out to a PST file.
How can I write the contents of 1 or several Outloo开发者_如何学JAVAk folders to a PST using .Net? [vb or c# no matter]
I was able to piece this code together from a variety of samples around the internet and MSDN docs. This will allow you to choose an outlook high level folder and will backup all folders underneath. In my case I didn't actually want mail folders so I exclude them.
Const BACKUP_PST_PATH As String = "C:\backup.pst"
Dim oFolder As Outlook.MAPIFolder = Nothing
Dim oMailbox As Outlook.MAPIFolder = Nothing
Dim app As New Outlook.Application()
Dim ns As Outlook.NameSpace = app.GetNamespace("MAPI")
Try
//if the file doesn not exist, outlook will create it
ns.AddStore(BACKUP_PST_PATH)
oFolder = ns.Session.Folders.GetLast()
oMailbox = ns.PickFolder()
For Each f As Outlook.Folder In oMailbox.Folders
If f.DefaultItemType <> Microsoft.Office.Interop.Outlook.OlItemType.olMailItem And f.FolderPath <> oFolder.FolderPath Then
f.CopyTo(oFolder )
End If
Next
ns.RemoveStore(oFolder)
Catch ex As Exception
ns.RemoveStore(oFolder)
IO.File.Delete(BACKUP_PST_PATH)
Throw ex
End Try
C# version:
public Store CreateStore(string path)
{
Application outlookApplication = new ();
Store newPst = null;
NameSpace outlookNamespace = outlookApplication.GetNamespace("mapi");
outlookNamespace.Session.AddStore(path);
foreach (Store store in outlookNamespace.Session.Stores)
{
if (store.FilePath == path)
{
newPst = store;
break;
}
}
return newPst;
}
精彩评论