Below is the code to add user in SharePoint group programmatically:
using (SPSite site = new SPSite(Respective Site URL))
{
using (SPWeb web = site.OpenWeb())
{
try
{
SPUser requiredUser = web.EnsureUser("domainname\\username");
if (requiredUser != null)
{
SPGroup requiredGroup = web.Groups["groupName"];
if (requiredGroup != null)
requiredGroup.AddUser(requiredUser);
}
}
catch (Exception ex)
{
}
}
}
using (SPSite site = new SPSite(Respective Site URL))
{
using (SPWeb web = site.OpenWeb())
{
try
{
SPUser requiredUser = web.EnsureUser("domainname\\username");
if (requiredUser != null)
{
SPGroup requiredGroup = web.Groups["groupName"];
if (requiredGroup != null)
requiredGroup.AddUser(requiredUser);
}
}
catch (Exception ex)
{
}
}
}