jgok222
jgok222

Reputation: 414

Adding a folder to a pst file from outlook in c#

I have been trying to find a way to add a folder to a pst file from c#

I have tried a whole bunch of code to try and get this to work and this is the one that seems to be most likly to be correct (as it is whats on the MSDN) but still does not work

Main {

Outlook._Application OutlookObject = new Outlook.Application();
            Outlook.Store NewPst = null;
           // create the pst file
            string pstlocation = "C:\\Users\\Test\\Desktop\\PST\\Test.pst";
            try
        {
            OutlookObject.Session.AddStore(pstlocation);

            foreach (Outlook.Store store in OutlookObject.Session.Stores)
            {
                if (store.FilePath == pstlocation)
                {
                    // now have a referance to the new pst file
                    NewPst = store;
                    Console.WriteLine("The Pst has been created");
                }
            }
        }
        catch
        { }
        // create a folder or subfoler in pst
        Outlook.MAPIFolder NewFolder;

        NewFolder = NewPst.Session.Folders.Add("New Test Folder", Type.Missing);
}

This code creates a new PST File and then trys to add a folder to it however the last line of code:

New NewFolder = NewPst.Session.Folders.Add("New Test Folder", Type.Missing);

Gets the error "The operation failed." and "Invalid Cast Exception" can some one point out what i am doing wrong

Thanks in advance

Upvotes: 2

Views: 4310

Answers (1)

Joshua Honig
Joshua Honig

Reputation: 13225

You need to use Store.GetRootFolder() to get a handle to the root folder of that store (not Store.Session). So you would use:

// create a folder or subfolder in pst    
Outlook.MAPIFolder pstRootFolder = NewPst.GetRootFolder();
Outlook.MAPIFolder NewFolder = pstRootFolder.Folders.Add("New Test Folder");

I recommend bookmarking both of the following: The PIA documentation isn't always complete, so it's worth checking out the COM documentation as well for complete class and member info.

Upvotes: 5

Related Questions