在 C# 中从 Outlook 添加文件夹到 pst 文件

jgo*_*222 2 .net c# outlook

我一直在尝试找到一种从 C# 将文件夹添加到 pst 文件的方法

我已经尝试了一大堆代码来尝试让它工作,这似乎是最有可能正确的代码(因为它是 MSDN 上的内容),但仍然不起作用

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);
}
Run Code Online (Sandbox Code Playgroud)

此代码创建一个新的 PST 文件,然后尝试向其中添加一个文件夹,但最后一行代码:

New NewFolder = NewPst.Session.Folders.Add("New Test Folder", Type.Missing);
Run Code Online (Sandbox Code Playgroud)

收到错误“操作失败”。和“无效的演员异常”有人可以指出我做错了什么吗

提前致谢

Jos*_*nig 5

您需要使用来获取该商店的Store.GetRootFolder()根文件夹的句柄(不是)。所以你会使用: Store.Session

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

我建议为以下两项添加书签: PIA 文档并不总是完整的,因此还值得查看 COM 文档以获取完整的类和成员信息。