Introduction:
In this article we will discuss how to add a user to web site using SharePoint 2010 object model. Also you can check my last article on:
Description:
using (SPSite site = new SPSite("http://Site URL"))
{
using (SPWeb web = site.OpenWeb())
{
web.SiteUsers.Add("EnjoySharePoint\\TestUser", "contact@enjoysharepoint.com","EnjoySharePoint Test User", null);
SPUser userAdded = web.SiteUsers["EnjoySharePoint\\TestUser"];
}
}
This add method will ignore if the user is already exists in the site.
Similarly we can also use the EnsureUser method which will check wether the user is already exists or not like below:
using (SPSite site = new SPSite("http://Site URL"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser userAdded = web.EnsureUser("EnjoySharePoint\\TestUser");
}
}