Jacob Nguyen
Jacob Nguyen

Reputation: 11

How to add ACTIVE DIRECTORY user to Sharepoint group

I got an exception when executing this snippet code

     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;
                    }
                }
            }
             });

PLease guide me. Thanks in advance.

Upvotes: 0

Views: 919

Answers (1)

EG.
EG.

Reputation: 136

I don’t know what your exact exception is, but you can try to do following changes:

  1. Instead of

    SPUser spUser = web.AllUsers[userName];

use (it will ensure that user exists on the web)

SPUser spUser = web.EnsureUser(userName);
  1. Instead of

    SPGroup spGroup = web.Groups[groupName];

use (Groups collection contains only groups that are defined on the current sub web)

SPGroup spGroup = web.SiteGroups[groupName];
  1. There is no need to check (spGroup != null) because if group is not found then always exception will be thrown.

Upvotes: 2

Related Questions