Delete an user in Active Directory via C#
I'm trying to delete an user in Active Directory via C#.When I attempt to run the following the code,I got an error.
Error Message:
A local error has occurred
Code:
开发者_JAVA技巧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();
I have an ASP.Net website running local that our IT team uses to delete AD accounts, and it seems to work ok. I remember when I was developing this application there were a lot of nuances I had to deal with, which can make it painful to figure out what's going on with AD. Here is the code I am using (in 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
Looking at your code, here are some ideas that come to mind:
- Try using dsrc.PropertiesToLoad.Add("sAMAccountName")
- Try adding a call to ent.CommitChanges()
- Can you verify the path and credentials are correct, say, using a command-line AD query tool?
- Can you determine specifically what line the error occurs on?
精彩评论