Adding a new SPUser to a Web

Adding a new SPUser to a Web

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:

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

[code lang="csharp"]
SPUser user = SPWeb.EnsureUser(@’AccountHere’)[/code]

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!!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">