How to get/update 'Contacts' within Active Directory?

后端 未结 2 1922
天命终不由人
天命终不由人 2020-12-05 17:03

is there a way to find and update the contacts in Active Directory? I\'m building a sample C# .NET application to achieve this task. I would appreciate any code.

2条回答
  •  猫巷女王i
    2020-12-05 17:33

    I think you mean updating properties on a user object in Active Directory. And yes this is possible.

    With .Net 3.5 we got the System.DirectoryServices.AccountManagement namespace which makes dealing with AD a lot simpler compared to what was in the System.DirectoryServices namespace before.

    Typically to modify properties of a user (if you have access to save) you would do something like:

    string sUserName = "someusertoload";
    string sDomain = "test.local";
    string sDefaultOU = "OU=test,DC=test,DC=local";
    string sServiceUser = "userwithrights";
    string sServicePassword = "somepassword";
    PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU,ContextOptions.SimpleBind, sServiceUser, sServicePassword);
    UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
    oUserPrincipal.GivenName = "new givenname";
    oUserPrincipal.Save();
    

    You can find a some helper methods here.

    Code sample for .Net 2.0 which retrieves a user with username "john" and updates the street address of the user. You might have to add credentials to the first line if the app running user don't have rights to edit content.

    DirectoryEntry root = new DirectoryEntry("LDAP://server/DC=test,DC=local");
    DirectorySearcher searcher = new DirectorySearcher( root, "(&(objectCategory=person)(objectClass=user)(sAMAccountName=john))" );
    SearchResult result = searcher.FindOne();
    DirectoryEntry user = result.GetDirectoryEntry();
    user.Properties["streetAddress"][0] = "My Street 12";
    user.CommitChanges();
    

提交回复
热议问题