使用C#更新Active Directory中的用户电子邮件地址

时间:2014-01-02 11:25:49

标签: asp.net c#-4.0 active-directory

我正在尝试使用以下代码更新Active Directory中用户的电子邮件地址。它已成功执行,但Active Directory中的电子邮件地址不会更改。

我该如何解决?

try
{
      using (var context = new PrincipalContext(ContextType.Domain, "yurs.yucc"))
      {
          if (context.ValidateCredentials(username, password))
          {
               UserPrincipal usrPrincipal = new UserPrincipal(context);
               usrPrincipal.EmailAddress = "raedsaleh11@gmail.com";                       
          }
      }
}
catch (Exception ex)
{
    // TODO: log exception
}

1 个答案:

答案 0 :(得分:2)

更新后,您需要保存用户主体....

try
{
    using (var context = new PrincipalContext(ContextType.Domain, "yurs.yucc"))
    {
       if (context.ValidateCredentials(username, password))
       {
          // find the user specified by "username"
          UserPrincipal usrPrincipal = UserPrincipal.FindByIdentity(context, username);

          if(usrPrincipal != null)
          {
              // if found, update e-mail address 
              usrPrincipal.EmailAddress = "raedsaleh11@gmail.com";

              // call .Save() to persist your changes! 
              usrPrincipal.Save();
          }
       }
   }
}
catch (Exception ex)
{
   // TODO: log exception
}