Reputation: 11
I got an exception when executing this snippet code
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteUrl.Trim()))
{
using (SPWeb web = site.OpenWeb())
{
try
{
web.AllowUnsafeUpdates = true;
SPUser spUser = web.AllUsers[userName];
if (spUser != null)
{
SPGroup spGroup = web.Groups[groupName];
if (spGroup != null)
spGroup.AddUser(spUser);
}
}
catch (Exception ex)
{
this.TraceData(LogLevel.Error, "Error at function Named [AddUserToSPGroupWidget.AddUserToGroup] . With Error Message: " + ex.ToString());
}
finally
{
web.AllowUnsafeUpdates = false;
}
}
}
});
PLease guide me. Thanks in advance.
Upvotes: 0
Views: 919
Reputation: 136
I don’t know what your exact exception is, but you can try to do following changes:
Instead of
SPUser spUser = web.AllUsers[userName];
use (it will ensure that user exists on the web)
SPUser spUser = web.EnsureUser(userName);
Instead of
SPGroup spGroup = web.Groups[groupName];
use (Groups collection contains only groups that are defined on the current sub web)
SPGroup spGroup = web.SiteGroups[groupName];
Upvotes: 2