【问题标题】:Update user email address in Active Directory using C#使用 C# 更新 Active Directory 中的用户电子邮件地址
【发布时间】:2014-01-02 11:25:48
【问题描述】:

我正在尝试使用以下代码更新 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
}

【问题讨论】:

  • 虽然不是您问题的答案,但您不应使用空的 catch 块,异常将被抑制。使用它不是一个好习惯。

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


【解决方案1】:

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

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
}

【讨论】:

  • 我尝试保存,但遇到以下异常:在保存之前,必须将 SamAccountName 或 Name 分配给此商店中新创建的 Principal 对象。
  • @RaedAlsaleh:嗯,在您的代码中,您正在创建一个 new 用户 - 这就是您想要的吗?我预计您想要检索现有用户并更新它?如果您确实创建了一个新用户,那么是的,samAccountName 是必填字段必须在保存前设置
  • @RaedAlsaleh:所以您必须首先找到用户! - 您的代码目前只是创建一个空的新用户。查看我的回复 - 我正在使用 username 查找该用户
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多