Add User To SharePoint Group Programmatically

Introduction:

In this article I will describe that how to add Share point user to share point group programmatically.

This will use below terms:-
1. AllowUnsafeUpdates: Before we update we will set AllowUnsafeUpdates to true.
2. SPGroup: We will create object sharepoint group in which we need to user.
3. AddUser: SPGroup.AddUser will add user into group.

The Code:-

Here I am going to detail about a generic function in which you pass group name and user name, then function will add user into group. For deployment, WSP creation and feature basic; please read below articles:-
http://sharepoint.infoyen.com/2012/04/01/create-webpart-in-sharepoint step by step using WSP/
http://sharepoint.infoyen.com/2012/04/22/feature-receiver-in-sharepoint/

See below detailed code:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// groupName will be string for e.g. "Site Owner"
// userLoginAccName will be "DomainName\UserName" for e.g. "Infoyen\\avinash"
public void AddUserToGroup(string groupName, string userLoginAccName)
{
	// you can also use SPContext to get SPWeb object
	Uri sitePath = new Uri("http://localhost/");
 
    using (SPSite site = new SPSite(sitePath.ToString()))
    {
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                SPUser requiredUser = web.EnsureUser[userLoginAccName];
 
                if (requiredUser != null)
                {
                    SPGroup requiredGroup = web.Groups[groupName];
                    if (requiredGroup != null)
                    requiredGroup.AddUser(requiredUser);
                }
            }
            catch (Exception ex){//Handle exception
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }
}

Thanks!
Avinash

calendarJune 25, 2012 · cardInfoyen · comments2 Comments
tagTags: ,  · Posted in: General, MOSS, Security, SharePoint

2 Responses

  1. Sandeep - June 29, 2012

    Thanks.

  2. Sandeep - June 29, 2012

    Thanks this worked

Leave a Reply

Spam Protection: , required

myworldmaps infoyen