You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET中如何关闭已归档的Outlook .pst文件?

准确移除临时添加的Outlook PST文件

问题核心是调用AddStore后,Outlook对象模型中新增Store的FilePath属性不会立即同步,导致无法通过路径直接匹配。正确的做法是通过Store的EntryID来追踪新增的存储,步骤如下:

  1. 添加PST前,记录当前所有Store的EntryID
  2. 添加目标PST后,对比找到新增的Store
  3. 通过该Store的根文件夹调用RemoveStore完成移除

VB代码实现

Dim olApp As New Outlook.Application()
Dim oNS As Outlook.NameSpace = olApp.GetNamespace("mapi")
Dim sStore As String = "[path to .pst file]"

' 记录添加前所有Store的EntryID
Dim originalStoreIds As New HashSet(Of String)()
For Each store As Outlook.Store In oNS.Session.Stores
    originalStoreIds.Add(store.EntryID)
Next

' 添加目标PST
oNS.Session.AddStore(sStore)

' 找到新增的Store
Dim targetStore As Outlook.Store = Nothing
For Each store As Outlook.Store In oNS.Session.Stores
    If Not originalStoreIds.Contains(store.EntryID) Then
        targetStore = store
        Exit For
    End If
Next

' 处理PST内容(读取邮件等操作)
' ...

' 移除目标PST
If targetStore IsNot Nothing Then
    oNS.Session.RemoveStore(targetStore.GetRootFolder())
End If

' 清理Outlook对象
olApp.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(oNS)
System.Runtime.InteropServices.Marshal.ReleaseComObject(olApp)

C#代码实现

using Outlook = Microsoft.Office.Interop.Outlook;

var olApp = new Outlook.Application();
var oNS = olApp.GetNamespace("mapi");
string sStore = @"[path to .pst file]";

// 记录添加前所有Store的EntryID
var originalStoreIds = new HashSet<string>();
foreach (Outlook.Store store in oNS.Session.Stores)
{
    originalStoreIds.Add(store.EntryID);
}

// 添加目标PST
oNS.Session.AddStore(sStore);

// 找到新增的Store
Outlook.Store targetStore = null;
foreach (Outlook.Store store in oNS.Session.Stores)
{
    if (!originalStoreIds.Contains(store.EntryID))
    {
        targetStore = store;
        break;
    }
}

// 处理PST内容
// ...

// 移除目标PST
if (targetStore != null)
{
    oNS.Session.RemoveStore(targetStore.GetRootFolder());
}

// 清理对象
olApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oNS);
System.Runtime.InteropServices.Marshal.ReleaseComObject(olApp);

关键说明

  • 使用EntryID而非FilePath:EntryID是Outlook中每个Store的唯一标识,添加后会立即生成,不会出现延迟同步的问题
  • 必须调用Quit()而非Close():olApp.Close()仅关闭窗口,Quit()才会彻底终止Outlook进程,确保配置变更生效
  • 手动释放COM对象:避免Outlook进程残留

内容的提问来源于stack exchange,提问作者PSU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 07:40:22