Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Outlook folders to a PST using .Net? [vb or c# no matter]

like image 225
brendan Avatar asked Nov 12 '09 19:11

brendan


1 Answers

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
like image 193
brendan Avatar answered Oct 03 '22 07:10

brendan