In this article I am going to explain how we can add a
user in SharePoint 2010 site programmatically. Here we have a Site Url and
Group already define in that site. Below is the code to show to add user in
SharePoint group:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace ADD_User
{
class Program
{
static void Main(string[]
args)
{
string
FileUrl = string.Empty;
string
Member = string.Empty;
string
Visitor = string.Empty;
string
UserName = string.Empty;
string
Email;
string
UserType;
string
UserEmail = string.Empty;
SPGroup
spGroup = null;
try
{
FileUrl = "http://localhost:1000/";
//Already
Define Group
Member = "DotNetCodesgSite Members";
Visitor = "DotNetCodesgSite Visitors";
UserType = "Admin";
UserName = "Rahul";
//Open
Site
SPSite
spSite = new SPSite(FileUrl);
SPWeb
spWeb = spSite.OpenWeb();
/////For
getting user details//////////////////////
SPUser
user = spWeb.EnsureUser(UserName);
SPListItem
list = spWeb.SiteUserInfoList.Items.GetItemById(user.ID);
int
user_id = int.Parse(user.ID.ToString());
Console.WriteLine("User Name=" + UserName);
Email = user.Email;
UserName = user.Name;
Console.WriteLine("User Email=" + Email);
Console.WriteLine("UserName=" + UserName);
//////////////////////////////////////////////////
if
(UserType == "Admin")
{
//Open
group
spGroup =
spWeb.SiteGroups[Member];
}
else
if (UserType == "Visitor")
{
//Open
group
spGroup =
spWeb.SiteGroups[Visitor];
}
//Add
and update group with new user
if
(!UserName.Contains(@"\"))
{
string
domain = "MyDomain";
UserName = domain +
UserName;
}
spGroup.AddUser(UserName,
UserEmail, UserName, "Added by
UserControl");
spGroup.Update();
string
ErrorMessage = "Success in Adding user in
SharePoint Site.";
string
ErrorCode = "Success";
Console.Read();
}
catch
(Exception ex)
{
string
ErrorMessage = ex.Message.ToString();
string
ErrorCode = "Failed";
Console.WriteLine(ex.Message.ToString());
Console.Read();
}
finally
{
//spWeb.Close();
//spSite.Close();
}
}
}
}