Suppose you need to perform some actions on a SharePoint user such as role assignment, but you are unsure if the user exists within the site you are currently working with.  One solution, which I have always used, is to check for the existence of the user within the site and if they do not exist, write some custom code to add them.

Well recently I found a method in the SharePoint object model that will handle this for you.  The “EnsureUser” method of the SPWeb class does exactly this.  It will check to see if the user account exists on the current site and if it doesn’t, it will create the user account for you.

SPSite site = new SPSite("http://localhost");
SPWeb web = site.RootWeb;

This has been a huge time saver for me as I have always written custom code to handle this.

MSDN Documentation:

Tagged on:

Leave a Reply