如何获取用于交换公共文件夹的所有电子邮件地址的列表?
将自行回复,将接受提供的最佳回复。
虽然您作为自己的答案发布的内容会起作用,但阅读有关您正在使用的方法和对象的文档以了解它们的局限性会有所帮助。如果您多次调用此代码,您最终会遇到内存泄漏。该foreach
语句不调用Dispose()
使用的对象,只调用它创建的枚举器。下面是一种更好的搜索目录的方法(尽管错误检查很少,也没有异常处理)。
public static void GetPublicFolderList()
{
DirectoryEntry entry = new DirectoryEntry("LDAP://sorcogruppen.no");
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=publicfolder))";
// Request the mail attribute only to reduce the ammount of traffic
// between a DC and the application.
mySearcher.PropertiesToLoad.Add("mail");
// See Note 1
//mySearcher.SizeLimit = int.MaxValue;
// No point in requesting all of them at once, it'll page through
// all of them for you.
mySearcher.PageSize = 100;
// Wrap in a using so the object gets disposed properly.
// (See Note 2)
using (SearchResultCollection searchResults = mySearcher.FindAll())
{
foreach (SearchResult resEnt in searchResults)
{
// Make sure the mail attribute is provided and that there
// is actually data provided.
if (resEnt.Properties["mail"] != null
&& resEnt.Properties["mail"].Count > 0)
{
string email = resEnt.Properties["mail"][0] as string;
if (!String.IsNullOrEmpty(email))
{
// Do something with the email address
// for the public folder.
}
}
}
}
}
DirectorySearcher.SizeLimit的注释表明如果大小限制高于服务器确定的默认值(1000 个条目),则忽略大小限制。分页允许您在需要时获取所需的所有条目。
DirectorySearcher.FindAll()的注释提到需要释放 SearchResultCollection 以释放资源。将其包装在using
语句中可以清楚地表明您作为程序员的意图。
如果您使用的是 Exchange 2007 或 2010,您还可以安装 Exchange 管理工具并使用 powershell cmdlet 来查询您的公用文件夹。您可以务实地创建一个 powershell 运行空间并直接调用 Exchange cmdlet,而实际上不需要用户与之交互的控制台。
以下代码将获取公共文件夹的所有电子邮件地址列表作为交换。
public static void GetPublicFolderList()
{
DirectoryEntry entry = new DirectoryEntry("LDAP://FakeDomain.com");
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=publicfolder))";
mySearcher.SizeLimit = int.MaxValue;
mySearcher.PageSize = int.MaxValue;
foreach (SearchResult resEnt in mySearcher.FindAll())
{
if (resEnt.Properties.Count == 1)
continue;
object OO = resEnt.Properties["mail"][0];
}
}
如果您想要公用文件夹的所有电子邮件地址,
消除:
object OO = resEnt.Properties["mail"][0];
添加: for (int counter = 0; counter < resEnt.Properties["proxyAddresses"].Count; counter++)
{
string Email = (string)resEnt.Properties["proxyAddresses"][counter];
if (Email.ToUpper().StartsWith("SMTP:"))
{
Email = Email.Remove(0, "SMTP:".Length);
}
}