Friday 16 December 2011

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

No comments:

Post a Comment