c#目录服务双添加到列表
本文关键字:列表 添加 目录服务 | 更新日期: 2023-09-27 18:19:01
我有一个目录服务方法从Active directory收集机器并将它们作为List<>
返回。
代码是:
public static List<string> PCsAndAttributes(string PCName, string AttributeToRead)
{
List<string> toReturn = new List<string>();
try
{
string LdapPath = "LDAP://corp.company.com";
DirectoryEntry computer = new DirectoryEntry(LdapPath);
DirectorySearcher search = new DirectorySearcher(PCName);
string searchAtt = "Name";
search.Filter = "(" + searchAtt + "=" + PCName + ")";
search.PropertiesToLoad.Add(AttributeToRead);
SearchResultCollection results = search.FindAll();
foreach (SearchResult result in results)
{
ResultPropertyCollection PCS = result.Properties;
if (!(toReturn.Contains(Convert.ToString(PCS))))
{
toReturn.Add(Convert.ToString(PCS[AttributeToRead][0]));
}
}
return toReturn;
}
catch (Exception err)
{
toReturn.Add(err.Message);
return toReturn;
}
}
由于某种原因,这是在我的树视图中创建两台计算机。我99%肯定错误在这个阶段,但我无法消除重复项。
下面是treeview节点代码:
private void UpdateLists()
{
List<string> AdFinds = ProfileCleaner.smallClasses.AdClasses.PCsAndAttributes(txtComputers.Text, "Name");
lblCount.Text = "PC Count: " + AdFinds.Count();
foreach (string PC in AdFinds)
{
string online = ProfileCleaner.smallClasses.PingIt.Pingit(PC);
if (online == "Success")
{
TreeNode pNode = treePCs.Nodes.Add(PC);
pNode.Checked = true;
string OS = ProfileCleaner.smallClasses.OsVersion.GetOsVersion.OSVersion(PC);
string SubPath = null;
if (OS == "6")
{
SubPath = @"'C$'Users'";
}
else
{
SubPath = @"'C$'Documents and Settings'";
}
try
{
string[] usrs = Directory.GetDirectories(@"''" + PC + SubPath);
foreach (string usr in usrs)
{
List<string> noAdds = new List<string>();
noAdds.Add("admin"); noAdds.Add("Administrator");
string[] lName = usr.Split('''');
string user = Convert.ToString(lName[lName.Length - 1]);
if (!(noAdds.Contains(user)))
{
pNode.Nodes.Add(usr);
}
}
}
catch (Exception folderErr)
{
}
}
}
}
谁能告诉我为什么我从活动目录中得到两台机器?
我试图捕捉和消除,也许是我的逻辑,但尝试这样的事情:
if (!(myList.contains(NewMachine)) { }
并不能阻止他们。
在活动目录中,计算机既是用户又是计算机。您的搜索字符串应该是search.Filter = "(&(" + searchAtt + "=" + PCName + ")(objectclass=computer))";
如果你想避免重复应该:
if (!(toReturn.Contains(Convert.ToString(PCS[AttributeToRead][0]))))
我有兴趣知道为什么AD返回副本。:)