我正在尝试编写一个 C# 控制台应用程序,该应用程序可以通过编程方式更新全局地址列表 (GAL) 中的 Outlook 通讯组列表 (DL)。 我有权更新此 DL。 我可以使用 Outlook 在我的 PC 上以交互方式执行此操作,并且可以使用 Win32::NetAdmin::GroupAddUsers
在 Perl 代码中执行此操作。
添加对 COM 库"Microsoft Outlook 14.0 对象库"的引用后,然后通过以下方式访问:
using Outlook = Microsoft.Office.Interop.Outlook;
我可以成功地从DL中读取,甚至可以在正在搜索的"主"DL中递归。 这是工作代码(本文不需要批评):
private static List<Outlook.AddressEntry> GetMembers(string dl, bool recursive)
{
try
{
List<Outlook.AddressEntry> memberList = new List<Outlook.AddressEntry>();
Outlook.Application oApp = new Outlook.Application();
Outlook.AddressEntry dlEntry = oApp.GetNamespace("MAPI").AddressLists["Global Address List"].AddressEntries[dl];
if (dlEntry.Name == dl)
{
Outlook.AddressEntries members = dlEntry.Members;
foreach (Outlook.AddressEntry member in members)
{
if (recursive && (member.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeDistributionListAddressEntry))
{
List<Outlook.AddressEntry> sublist = GetMembers(member.Name, true);
foreach (Outlook.AddressEntry submember in sublist)
{
memberList.Add(submember);
}
}
else {
memberList.Add(member);
}
}
}
else
{
Console.WriteLine("Could not find an exact match for '" + dl + "'.");
Console.WriteLine("Closest match was '" + dlEntry.Name +"'.");
}
return memberList;
}
catch
{
// This mostly fails if running on a PC without Outlook.
// Return a null, and require the calling code to handle it properl
// (or that code will get a null-reference excception).
return null;
}
}
我可以使用它的输出来仔细检查成员,所以我想我对 DL/成员对象有点了解。
但是,以下代码不会将成员添加到 DL:
private static void AddMembers(string dl)
{
Outlook.Application oApp = new Outlook.Application();
Outlook.AddressEntry ae = oApp.GetNamespace("MAPI").AddressLists["Global Address List"].AddressEntries[dl];
try {
ae.Members.Add("EX", "Tuttle, James", "/o=EMC/ou=North America/cn=Recipients/cn=tuttlj");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
ae.Update();
}
此处定义了要Members.Add()
的参数,我的代码中显示的值完全来自从另一个 DL 检查我自己的 Member 对象。
显示的异常只是"书签无效"。 之前有人问过类似的问题,但解决方案是使用 P/Invoke 或 LDAP。 我真的不知道如何使用 P/Invoke(严格来说是一个 C# 和 Perl 程序员,而不是 Windows/C/C++ 程序员),而且我无法访问 LDAP 服务器,所以我真的很想通过 Microsoft.Office.Interop.Outlook
对象来工作。
任何帮助将不胜感激!
在尝试了几个不同的 .NET 对象之后,使用在 .NET 中添加和删除用户组中发布的System.DirectorServices.AccountManagement
最终为我编写了代码。 结束我自己的问题。