首页 > 解决方案 > C# - 目录服务 - 大约每月一次随机接收错误

问题描述

我有一个 Windows 服务,它查询 Active Directory 用户信息并将其写入数据库。随机(我会说每月一次),它会出错并且不会成功重新启动。我想知道是否有人会知道为什么会随机出现此错误?

ERROR - 发生本地错误。

在 System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()
在 System.DirectoryServices.AccountManagement.ADEntriesSet.MoveNext()
在 System.DirectoryServices.AccountManagement.FindResultEnumerator 1.MoveNext() at System.DirectoryServices.AccountManagement.FindResultEnumerator1.System.Collections.IEnumerator.MoveNext()

它似乎指向最后一行错误(在遍历集合时):

int num1 = 0;
int num2 = 0;

DateTime now1 = DateTime.Now;

PrincipalContext AD = new PrincipalContext(ContextType.Domain, "ourdomain.org");

UserPrincipal userPrincipal = new UserPrincipal(AD);

PrincipalSearcher search = new PrincipalSearcher(userPrincipal);
var all = search.FindAll();

int userCount = 0;

foreach (UserPrincipal result in all)
{
    // some code
}

标签: c#active-directorydirectoryservices

解决方案


我建议重写您的代码以使用DirectorySearcher. 它可能会解决您的问题,但即使没有,您也应该能够获得有关可能出现问题的更多信息。你的循环会运行得更快。PrincipalSearcher无论如何只是一个包装器DirectorySearcher,但是您会失去很多控制和性能。

这是一个可能看起来像的示例:

var search = new DirectorySearcher(new DirectoryEntry()) {
    PageSize = 1000, //this is required if you expect more than 1000 results
    Filter = "(&(objectClass=user)(objectCategory=person))" //all users
};

//tell it which properties you want to return, otherwise it will return everything
search.PropertiesToLoad.Add("mail");

using (var results = search.FindAll()) {
    foreach (SearchResult result in results) {
        try {
            // some code

            // Get attributes from search results like:
            // (string) result.Properties["mail"][0]
            
        } catch (Exception e) {
            // log exception
            // use result.Path to show you which user it choked on
        }
    }
}

确保更新search.PropertiesToLoad以包含您希望从搜索结果中看到的属性。

还要注意,您可以捕获任何异常并将其记录Path到导致异常的用户。然后您可以检查该用户并查看它有什么不同。

我写了一篇关于在针对 AD 进行编程时获得更好性能的文章,它可以帮助您:Active Directory:更好的性能


推荐阅读