I want add user in ActiveDirectory.
I use this code
private SPUser CreateUser(string strLoginName, string strEMail,
string strName, string strNotes, string strSiteURL)
{
SPUser spReturn = null;
SPSite spSite = null;
SPWeb spWeb = null;
try
{
//Open the SharePoint site
spSite = new SPSite(strSiteURL);
spWeb = spSite.OpenWeb();
//Assign role and add user to site
SPRoleAssignment spRoleAssignment =
new SPRoleAssignment(strLoginName, strEMail, strName, strNotes);
//Using Contribute, might need high access
SPRoleDefinition spSPRoleDefinition =
spWeb.RoleDefinitions["Contribute"];
spRoleAssignment.RoleDefinitionBindings.Add(spSPRoleDefinition);
spWeb.RoleAssignments.Add(spRoleAssignment);
//Update site
spWeb.Update();
spReturn = spWeb.AllUsers[strLoginName];
}
catch(Exception)
{
}
finally
{
spWeb.Close();
spSite.Close();
}
return spReturn;
}
when spWeb.RoleAssignments.Add(spRoleAssignment);
error :”Error:The user does not exist or is not unique “
EDIT
The following worked for me:
SPUser user = spWeb.EnsureUser(strLoginName);
SPRoleAssignment spRoleAssignment =
new SPRoleAssignment(user);
Your code will only grant Contribute access to an existing Active Directory user.
If you really want to create a new Active Directory user, see Create Active Directory user in .NET (C#).