2011-09-26 71 views
1

我試圖通過C#刪除Active Directory中的用戶。當我嘗試運行以下代碼時,出現錯誤。通過C#刪除Active Directory中的用戶

錯誤消息:

A local error has occurred 

代碼:

DirectoryEntry ent = new DirectoryEntry("LDAP://192.168.1.99/OU=FIRMA"); 
    ent.Username = "idm\administrator"; 
    ent.Password = "123123QQ"; 
    DirectorySearcher dsrc = new DirectorySearcher(ent); 
    dsrc.Filter = string.Format("(&(objectCategory=user)(SAMAccountName=adKullaniciadi))"); 
    DirectoryEntry silsunuya = ent.Children.Find("CN=adKullaniciadi","objectClass=person"); 
    ent.Children.Remove(silsunuya); 
    ent.Close(); 
    silsunuya.Close(); 
    dsrc.Dispose(); 

回答

1

我有一個ASP.Net網站運行的本地,我們的IT團隊使用刪除AD帳戶,它似乎工作確定。我記得當我開發這個應用程序時,我需要處理很多細微差別,這可能會讓我們很難弄清楚AD發生了什麼。下面是我使用(在VB.Net)代碼:

Public Shared Function GetUser(ByVal username As String) As DirectoryEntry 
    If String.IsNullOrEmpty(username) Then Return Nothing 

    Dim path As String = ConfigurationManager.ConnectionStrings("ADConnectionString").ConnectionString 
    Dim ds As New DirectorySearcher(path) 

    ds.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))" 
    ds.PropertiesToLoad.Add("sAMAccountName")   ' username 
    ds.PropertiesToLoad.Add("mail")   ' e-mail address 
    ds.PropertiesToLoad.Add("description") ' Bureau ID 
    ds.PropertiesToLoad.Add("company")  ' company name 
    ds.PropertiesToLoad.Add("givenname") ' first name 
    ds.PropertiesToLoad.Add("sn")   ' last name 
    ds.PropertiesToLoad.Add("name")   ' client name 
    ds.PropertiesToLoad.Add("cn")   ' common name 
    ds.PropertiesToLoad.Add("dn")   ' display name 
    ds.PropertiesToLoad.Add("pwdLastSet") 
    ds.SearchScope = SearchScope.Subtree 
    Dim results As SearchResult = ds.FindOne 

    If results IsNot Nothing Then 
     Return New DirectoryEntry(results.Path) 
    Else 
     Return Nothing 
    End If 
End Function 

Public Shared Sub DeleteUser(ByVal username As String, Optional ByVal useImpersonation As Boolean = False) 
    Dim user As DirectoryEntry = GetUser(username) 
    Dim ou As DirectoryEntry = user.Parent 
    ou.Children.Remove(user) 
    ou.CommitChanges() 
End Sub 

看你的代碼,這裏有一些想法浮現在腦海中:

  1. 嘗試使用dsrc.PropertiesToLoad.Add(」 sAMAccountName「)
  2. 嘗試將呼叫添加到ent.CommitChanges()
  3. 可以使用命令行AD查詢工具驗證路徑和憑證是否正確?
  4. 你能明確確定錯誤發生在哪一行嗎?
+0

我同意第2點。我認爲這將是問題。請參閱http://msdn.microsoft.com/zh-CN/library/system.directoryservices.directoryentry.commitchanges.aspx –

相關問題