C# Filter List of Active Directory Users 并返回 Active/Enable Users



我有一个从AD返回的用户列表,我需要对它们进行筛选,只返回活动用户。这是我的代码,但它不会返回任何用户。经过大量的谷歌搜索,我不知道遗漏了什么;

public static List<Models.ToolUser> ActiveUsers()
{
int unlimitedAccess;
//string userAccountControl;
string listEntry;
string fName;
string lName;
string unlimitedAccessGroup;
//This is getting the List of Users that I need to filter
List<Models.ToolUser> activeUserList = UIDal.GetFullWindowsUserList();
try
{
string filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
string[] propertiesToLoad = new string[1] { "name" };
using (DirectoryEntry de = GetDirectoryEntryWithGc())
using (DirectorySearcher searcher = new DirectorySearcher(de, filter, propertiesToLoad))
using (SearchResultCollection results = searcher.FindAll())
{
foreach (SearchResult result in results)
{
unlimitedAccess = 0;
fName = result.Properties["givenName"][0].ToString();
lName = result.Properties["sn"][0].ToString();
listEntry = fName + " " + lName;
var name = result.Properties["sAMAccountName"][0].ToString();
var u = new ToolUser
{
ToolUserId = 0,
DomainAccount = result.Properties["sAMAccountName"][0].ToString(),
FirstName = fName,
LastName = lName,
LoginId = "pc-" + result.Properties["sAMAccountName"][0].ToString(),
UnlimitedAccess = unlimitedAccess > 0,
};
activeUserList.Add(u);
}
}
}
catch
{
}
return activeUserList;
}

空的catch块是魔鬼。在继续之前,您至少应该记录异常。

在这种情况下,你的空catch块隐藏了真正发生的事情。你在这里得到了一个"索引超出范围"的异常:

fName = result.Properties["givenName"][0].ToString();

因为result.Properties["givenName"]是一个空集合(在索引0处没有元素(。正因为如此:

string[] propertiesToLoad = new string[1] { "name" };

您告诉搜索只返回找到的对象的name属性,但随后继续使用givenNamesnsAMAccountName。如果你打算使用这些属性,你需要告诉它返回这些属性:

string[] propertiesToLoad = new string[3] { "givenName", "sn", "sAMAccountName" };

也就是说,givenNamesn不是必需的属性。如果在找到的任何帐户上,这些属性都是空的,那么它们将根本不会出现在Properties集合中,并且您将再次遇到相同的异常。因此,在尝试使用这些属性之前,您应该测试这些属性是否确实存在。例如,如果属性不存在,这将检查变量并将其设置为空字符串:

fName = result.Properties.Contains("givenName") ? result.Properties["givenName"][0].ToString() : "";
lName = result.Properties.Contains("sn") ? result.Properties["sn"][0].ToString() : "";

最新更新