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