I have a directory services method to gather machines from Active Directory and return them as a List<>
.
The code is:
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;
}
}
For some reason, this is creating two of every computer in my treeview. I am 99% sure the error is at this stage, but I am unable to eliminate the duplicates.
Here is the treeview node code:
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)
{
}
}
}
}
Can someone tell me why I am getting two of every machine from Active Directory?
I have tried to capture and eliminate, perhaps its my logic, but trying things like:
if (!(myList.contains(NewMachine)) { }
Is not stopping them.