Thursday, December 10, 2009

Add User To SharePoint Group Programmatically



Let’s see how we can programmatically add a user to existing SharePoint user group . You can use the following method which has two string parameters, one for group name and other for user login name for get the above task done.
public void addUserToGroup(string groupName, string userLoginName)
{
    string strUrl = "http://mysite:5050/";
    using (SPSite site = new SPSite(strUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                SPUser spUser = web.EnsureUser[userLoginName];

                if (spUser != null)
                {
                    SPGroup spGroup = web.Groups[groupName];
                    if (spGroup != null)
                    spGroup.AddUser(spUser);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }
}
Here you should provide the login name in correct format (DomainName\UserName). For example you can call this method like follow,

addUserToGroup("Test Group", "SA\\saranga.rathnayaka");

Related Posts:

  • CAML & SPQuery in SharePoint Using Collaborative Application Markup Language (CAML)  queries with SPQuery and SPSiteDataQuery is a faster and more efficient way of retrievi… Read More
  • SharePoint User GroupsCheck User Group in SharePoint To store and manage permissions we can create User Groups in SharePoint. In this article I’ll discuss how you can che… Read More
  • What is SharePoint ? SharePoint, the fastest-growing product in the history of Microsoft is a collection of products and software elements which can be configured to run … Read More
  • Delete item from SharePoint List In my previous post SharePoint List C# Part 1 I discussed how we can add items to SharePoint list. We also have to delete items from a list. F… Read More
  • Deleting Features from SharePoint In one of my previous article I discussed about creating and deploying custom features to SharePoint server. Here I’m going to describe how you can r… Read More

2 comments:

  1. What about adding users to audiences programmtically?

    ReplyDelete
  2. Hi,The usual mistake of many new web designers is that they put so many colors on their Web Design Cochin that what they come up with is a virtual color palette that you cannot pinpoint what exactly is the color scheme being used.Thanks..........

    ReplyDelete