Friday, August 03, 2007

Programatically Add User to SharePoint 2007

There are a ton of articles out there detailing how to add a user to a SharePoint site; however, it's a struggle to find anything detailing how to perform the operation in a SharePoint 2007 environment.

private static void AddUser()
{
try
{
using (SPSite site = new SPSite("http://test1"))
{
ServerContext context = ServerContext.GetContext(site);
UserProfileManager profileManager = new UserProfileManager(context);

if (!profileManager.UserExists("senfo"))
{
UserProfile profile = profileManager.CreateUserProfile("senfo");

profile[PropertyConstants.WorkEmail].Value = "me@myaddress.com";
profile.Commit();
}
else
{
Console.WriteLine("User already exists...");
}
}
}
catch (UserNotFoundException err)
{
Console.WriteLine(err.ToString());
}
}


It's important to note that if you're using multiple membership providers that this code will throw the following Exception "No mapping between account names and security IDs was done". To correct the issue, add "MembershipProviderName:" in front of the username. For example, "SqlMembershipProvider:senfo".

No comments: