Adding a new SPUser to a Web

6 01 2009

I’ve been working on a console application this morning to add users from an Active Directory group to a specific SharePoint group. I was struggling when I came to add the users to the parent web -  SPWeb.Users.Add.

Even though I passed in all the required variables (Account, Display Name, Email and Notes), it kept giving me an InvalidOperationException error.

I began to Google around and this is when I came across this post by Mirjam on her blog:

http://www.sharepointblogs.com/mirjam/archive/2007/12/20/using-spweb-ensureuser-loginname-to-add-a-new-spuser-to-a-web.aspx

It seems if you use the EnsureUser function from the SDK –

SPUser user = SPWeb.EnsureUser(@’AccountHere’).

It will check to see if the login name exists as a valid user of the SharePoint site and if not it will add it.

Sidenote: Make sure you call an SPWeb.AllowUnsafeUpdates = true in order for the above to work and make sure you set it back to false after.

Pretty useful I think!!

Advertisements

Actions

Information

One response

16 08 2011
.Net Follower

HellO!
Very nice article. I worked with EnsureUser a lot and, eventually, I’ve developed a small method-wrapper for EnsureUser. It’s shown in my blog – http://dotnetfollower.com/wordpress/2011/05/sharepoint-wrapper-over-ensureuser/
Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: