SharePoint 2013: How to get user owner of a mysite personal site

Recently we stumbled upon a task to set some properties of a personal mysite site collection of a user – we wanted to get precisly the user (owner) whose the site collection is, not the user who is browsing the sitecollection (current user) nor the user who is running a script. We found two ways of doing this.

Get the site collection owner

The easiest way is just to get the site collection owner of the personal mysite site collection. This C# code would do the job:

using (var site = new SPSite(personalmysiteurl))
{
    var owner = site.Owner;
}

 

The problem would arise, if someone changes and plays with the site collection owners (seen that, been there).

Get the user from property bag of the root web

The other way of getting the user is to use an internal SharePoint’s property in the web porperty bag. It turns out that under a key, beautifully called “urn:schemas-microsoft-com:sharepoint:portal:profile:userprofile_guid” we can find the actual guid of the user:

using (var site = new SPSite(personalmysiteurl))
{
    using (var web = site.OpenWeb())
    {
        // Get user guid
        var userGuidString = web.AllProperties["urn:schemas-microsoft-com:sharepoint:portal:profile:userprofile_guid"];

        // Get user profile
        var context = SPServiceContext.GetContext(site);
        var userProfileManager = new UserProfileManager(context);
        Microsoft.Office.Server.UserProfiles.UserProfile userProfile = userProfileManager.GetUserProfile(userGuid);
    }
}

 

Happy coding!