[SharePoint Developer Tip of the Day] How to create a new user for an SPWeb

1 view
Skip to first unread message

Dave Graham

unread,
Mar 20, 2009, 6:54:26 PM3/20/09
to sharepoint-develo...@googlegroups.com

It seems that if a user needs to be added to a SPWeb object one should just call SPWeb.Users.Add. Unfortunately, this does not work and you will get an exception.  To add a user correctly you need to define the users access rights. This is most easily done using the predefined roles.  Here is a small foreign method that does the job correctly.

private void AddUser(SPWeb web, SPRoleType roleType, string login, string email, string name, string notes)

{

    SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(roleType);

    SPRoleAssignment roleAssignment = new SPRoleAssignment(login, email, name, notes);

    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);

    web.RoleAssignments.Add(roleAssignment);

}

Remember to always get SPRoleDefinition objects using the SPRoleDefinitionCollection.GetByType method and never using the [string] indexer.  The indexer takes the localized name of the role. Using a string like “Viewer” will work in English but will not in any other language. SPRoleType is an enumeration that is locale independent.



--
Posted By Dave Graham to SharePoint Developer Tip of the Day at 3/20/2009 03:52:00 PM
Reply all
Reply to author
Forward
0 new messages