【发布时间】:2012-06-01 19:50:03
【问题描述】:
是否可以使用 C# 读取 .PST 文件?我想将其作为一个独立的应用程序,而不是作为 Outlook 插件(如果可能的话)。
如果看到 other SO questions similar 提到 MailNavigator 但我希望在 C# 中以编程方式执行此操作。
我查看了 Microsoft.Office.Interop.Outlook 命名空间,但这似乎仅适用于 Outlook 插件。 LibPST 似乎能够读取 PST 文件,但这是用 C 语言编写的(抱歉 Joel,我没有 learn C before graduating)。
任何帮助将不胜感激,谢谢!
编辑:
感谢大家的回复!我接受了 Matthew Ruston 的回复作为答案,因为它最终将我引向了我正在寻找的代码。这是我开始工作的一个简单示例(您需要添加对 Microsoft.Office.Interop.Outlook 的引用):
using System;
using System.Collections.Generic;
using Microsoft.Office.Interop.Outlook;
namespace PSTReader {
class Program {
static void Main () {
try {
IEnumerable<MailItem> mailItems = readPst(@"C:\temp\PST\Test.pst", "Test PST");
foreach (MailItem mailItem in mailItems) {
Console.WriteLine(mailItem.SenderName + " - " + mailItem.Subject);
}
} catch (System.Exception ex) {
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
private static IEnumerable<MailItem> readPst(string pstFilePath, string pstName) {
List<MailItem> mailItems = new List<MailItem>();
Application app = new Application();
NameSpace outlookNs = app.GetNamespace("MAPI");
// Add PST file (Outlook Data File) to Default Profile
outlookNs.AddStore(pstFilePath);
MAPIFolder rootFolder = outlookNs.Stores[pstName].GetRootFolder();
// Traverse through all folders in the PST file
// TODO: This is not recursive, refactor
Folders subFolders = rootFolder.Folders;
foreach (Folder folder in subFolders) {
Items items = folder.Items;
foreach (object item in items) {
if (item is MailItem) {
MailItem mailItem = item as MailItem;
mailItems.Add(mailItem);
}
}
}
// Remove PST file from Default Profile
outlookNs.RemoveStore(rootFolder);
return mailItems;
}
}
}
注意:此代码假定已为当前用户安装并配置了 Outlook。它使用默认配置文件(您可以通过转到控制面板中的邮件来编辑默认配置文件)。对这段代码的一个主要改进是创建一个临时配置文件来代替默认配置文件,然后在完成后将其销毁。
【问题讨论】:
-
我不知道 AddStores 和 Stores 列表甚至存在于 Outlook API 中。好帖子!
-
我错过了什么吗?为什么我无法访问 OutlookNS 的 Stores 集合?它不是智能感知的。
-
您是否包括了“使用 Microsoft.Office.Interop.Outlook;”在你的代码中?
-
我做到了,我可以看到其他所有内容。我只是看不到 Outlook 命名空间的 stores 集合。我只是想到了一些东西...您引用了哪个版本的 Microsoft.Office.Interop.Outlook?我正在使用 11。
-
您也可以尝试使用 Aspose.Network for .NET 从 Outlook PST 文件中读取和提取 msg 文件。请访问http://www.aspose.com/documentation/.net-components/aspose.network-for-.net/read-outlook-pst-file-and-get-folders-and-subfolders-information.html了解更多信息。
标签: c# outlook outlook-2007 outlook-2003 pst