Skip to main content
2 of 2
added 313 characters in body
Vardhaman Deshpande
  • 10.5k
  • 1
  • 27
  • 52

Try the following code. It is always better to use the token of the system account instead of running all your code inside of SPSecurity.RunWithElevatedPriviledges(). The code is much stable and secure this way.

UPDATE: Since you are using your code in an Application Page, make sure you have called the SPUtility.ValidateFormDigest() method before any of your elevated code. If that does not work, try setting the web.AllowUnsafeUpdates = true of the newly created web.

SPUtility.ValidateFormDigest();

SPUserToken sysToken = SPContext.Current.Site.SystemAccount.UserToken;
using (SPSite site = new SPSite(newWebUrl,sysToken))
{
    using (SPWeb web = site.OpenWeb())
    {
        foreach (string gName in pPickers.Keys)
        {
            web.EnsureUser(web.CurrentUser.LoginName);
            PeopleEditor peopleEditor = pPickers[gName];

            foreach (PickerEntity entity in peopleEditor.ResolvedEntities)
            {
                string groupName = gName + " on " + web.Title;

                SPGroup group = web.Groups[groupName];
                SPUser user = web.EnsureUser(entity.Key);

                if (user != null)
                {
                    group.AddUser(user);
                    group.Update();
                }
            }
        }
    }
}
Vardhaman Deshpande
  • 10.5k
  • 1
  • 27
  • 52