Ads

Wednesday, 15 May 2013

C# code to 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 = "Site URL";
    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\\Khitan.riteyaz");

No comments:

Post a Comment

Ads