如何将ACTIVE DIRECTORY用户添加到Sharepoint组

时间:2010-05-24 10:08:46

标签: sharepoint

执行此代码段

时出现异常
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
            using (SPSite site = new SPSite(siteUrl.Trim()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    try
                    {
                        web.AllowUnsafeUpdates = true;
                        SPUser spUser = web.AllUsers[userName];


                        if (spUser != null)
                        {
                            SPGroup spGroup = web.Groups[groupName];
                            if (spGroup != null)
                                spGroup.AddUser(spUser);
                        }
                    }
                    catch (Exception ex)
                    {
                        this.TraceData(LogLevel.Error, "Error at function Named               [AddUserToSPGroupWidget.AddUserToGroup] . With Error Message: " + ex.ToString());

                    }
                    finally
                    {
                        web.AllowUnsafeUpdates = false;
                    }
                }
            }
             });

请指导我。提前谢谢。

1 个答案:

答案 0 :(得分:2)

我不知道您的确切异常是什么,但您可以尝试进行以下更改:

  1. 而不是

    SPUser spUser = web.AllUsers [userName];

  2. 使用(它将确保用户在网络上存在)

    SPUser spUser = web.EnsureUser(userName);
    
    1. 而不是

      SPGroup spGroup = web.Groups [groupName];

    2. use(组集合仅包含在当前子网站上定义的组)

      SPGroup spGroup = web.SiteGroups[groupName];
      
      1. 无需检查(spGroup!= null),因为如果找不到组,则会抛出异常。