Programmatically add users to SharePoint

Points you need to remember when you add user :
  • Always run the code with Eleveted Privillages. Also use Delegate.
  • Get SPWeb by abosolute URI, not relative
  • Set AllowUnsafeUpdates to true before adding user, and turn it off once user is added.
  • Remember, if you are using FBA, prefix the Membership Provider Name before the “username” i.e
    • defaultProvider + “:” + sUserName
    • fbademo:testuser
  • Always Dispose the SpWeb object after finishing everything.

Sample Code:

SPSecurity.RunWithElevatedPrivileges(delegate {

// get provider name

MembershipSection section = (MembershipSection)WebConfigurationManager.OpenWebConfiguration(“/”).GetSection(“system.web/membership”);

string defaultProvider = section.DefaultProvider;

// get site ref

SPWeb web = new SPSite(this.Request.Url.AbsoluteUri.Replace(this.Request.Url.LocalPath, “”)).OpenWeb();

// get memeber group

SPGroup associatedMemberGroup = web.AssociatedVisitorGroup;

web.AllowUnsafeUpdates = true;

// add user to group and update it

associatedMemberGroup.AddUser(defaultProvider + “:” + sUserName, sEmail, sUserName, “”);

associatedMemberGroup.Update();

web.AllowUnsafeUpdates = false;

web.Dispose();

});