简体   繁体   中英

How to programmatically set a user as the Site Collection Administrator in SharePoint

I am working on a SharePoint 2013 site. I'm trying to set a user as the Site Collection Administrator using the following code:

public void SetUserSiteCollectionAdmin(string siteUrl, string strUserName, string strEmail, string fullName)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteUrl))
                    {
                       using (SPWeb web = site.RootWeb)
                         {
                           web.AllowUnsafeUpdates = true;
                           web.AllUsers.Add(strUserName, strEmail, fullName, null);
                           SPUser spUser = web.SiteUsers[strUserName];

                           spUser.IsSiteAdmin = true;

                           spUser.Update();

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

When I go to 'Site Settings' in my SharePoint 2013 site, and open the 'Site Collection Administrators' list, I do see that user listed as the Site Collection Administrator.

All seems good. Now when I open this Site using the same username (who is just added this Site Collection Administrator list), I get message:

Sorry, this site hasn't been shared with you.

What other things do we need to do other than making the user as the 'Site Collection Administrator' any other settings am I missing here?

I suspect that this might have to do with how user identities are stored in the SharePoint content database. Have you tried examining the existing users to see precisely what is stored in the username property?

This page on my blog may or may not be related, but it describes how Forms Based users were stored quite strangely in the SharePoint Object Model...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM