Wednesday, February 17, 2010

Copying users from user profile to site users

Hi All,

One fine day I woke up and thought of doing some small code on user profile. Then I decided to copy all users from user profile to one site. Just for knowledge purpose and it worked. So I am going to show the steps to achieve this in this post.

Keep in mind that I’ve done it on my server only and I developed Windows Application to achieve this.

First, taken an object for your web in which you want to copy users.

You will need these references of assemblies.

using System;
using System.Windows.Forms;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using Microsoft.SharePoint;

and thenwriten down the following code. Just make sure that you have administrative rights to perform this operation.

SPSite objSite = new SPSite("{site URL}");
//Then obtain server context,
ServerContext svrContext = ServerContext.GetContext(objSite);
//Take User profile object
UserProfile myProfile = null;
UserProfileManager profileManager = new UserProfileManager(svrContext);
//Open the web.
SPWeb web = objSite.OpenWeb();

web.AllowUnsafeUpdates = true;

//Navigate through each user profile in profile manager
//and then add the users to the site with its login name.

foreach (UserProfile userprofile in profileManager)
if (profileManager.UserExists(userprofile.MultiloginAccounts[0]))
web.SiteUsers.Add(userprofile.MultiloginAccounts[0], "", "", "");



web.AllowUnsafeUpdates = false;

After performing this operation, just wait for some time. This is because initially you may see users Account name as DomainName\UserName, However after some time, These user names will be converted to the Actual user names.(the one that we see after welcome {user name} on top right corner).

Hope this will help.

No comments:

Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to