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");

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