8

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]

brendan
  • 29,308
  • 20
  • 68
  • 109

2 Answers2

12

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
brendan
  • 29,308
  • 20
  • 68
  • 109
  • um; where is the "pst" object declared and initialized? – akavel Jan 19 '10 at 15:56
  • ns.AddStore(BACKUP_PST_PATH) - this will create a PST if none exists at that location - ns.Session.Folders.GetLast() will then get you a handle to that PST/Folder – brendan Jan 19 '10 at 20:33
  • so the "pst" variable in your code (in 2 places) is a typo meant to be "oFolder"? – akavel Jan 20 '10 at 09:41
  • yep, works well with "oFolder". Thanks very much! Although in the end it seems I won't be able to use it for my needs anyway... – akavel Jan 21 '10 at 12:43
  • Can anyone share the complete source code.. I am not aware of .NET and also unable find any libraries in any other languages regarding outlook or PST. – Srinath Thota May 24 '19 at 12:04
1

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;
}
James John McGuire 'Jahmic'
  • 11,728
  • 11
  • 67
  • 78