Monday, 3 December 2012

Add User To SharePoint Group Programmatically


Introduction:

Below I found this article 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:-

This 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:-
// 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
Nikhil S.


Share This!


2 comments:

  1. it is really useful...........thx

    ReplyDelete
  2. here is a tool to add users to sharepoint group http://tanveerkhan-sharepoint.blogspot.com.au/2013/06/add-users-to-group-in-sharepoint.html

    ReplyDelete

Translate

Total Pageviews

Powered By Blogger · Designed By Seo Blogger Templates