2013-06-19 41 views
2

我有一個目錄服務方法來從Active Directory收集機器並將它們返回爲List<>C#目錄服務添加到列表

的代碼是:

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) 
       { 
       } 
      } 
     } 
    } 

誰能告訴我爲什麼我獲得兩個從Active Directory中的每臺機器的?

我試圖捕捉和消滅,也許它的我的邏輯,但在嘗試喜歡的東西:

if (!(myList.contains(NewMachine)) { } 

是不是阻止他們。

回答

2

在活動目錄中,計算機既是用戶又是計算機。您的搜索字符串應該是search.Filter = "(&(" + searchAtt + "=" + PCName + ")(objectclass=computer))";

+0

只要我讀了你的帖子,這是一個「杜」的時刻。所以,呃,並且非常感謝。 –

+0

沒問題,很樂意幫忙 –

0

如果你想避免重複應該是:

if (!(toReturn.Contains(Convert.ToString(PCS[AttributeToRead][0])))) 

我是想知道爲什麼AD返回重複。 :)

+0

我曾嘗試過這種方法,但沒有奏效。事實證明,這是愚蠢的錯誤。我將計算機查找稱爲用戶查找,因此當我執行FindAll()時,發現用戶帳戶和計算機帳戶James McShane指出。我在廣告中度過了足夠的時間,我真的應該抓住這一點。 –