Adding users to MOSS via code

Have you been adding users to your MOSS sites via code? Have you received the dreaded "Operation is not valid due to the current state of the object." error? Rejoice, there is a simple operation that will save you all sorts of typing.


//This actually creates the SPUser object
SPUser sUser = currentWeb.EnsureUser(UserAccount)

//This grants contributor rights to the SPUser
SPRoleAssignment ra = new SPRoleAssignment(sUser);
SPRoleDefinition rd = currentWeb.RoleDefinitions.GetByType(SPRoleType.Contributor);
ra.RoleDefinitionBindings.Add(rd);
currentWeb.RoleAssignments.Add(ra);
currentWeb.Update();

When using this approach, there is a slight delay between the Update on the currentWeb and the availability of the new permissions. So if you call that site as the aforementioned user you may get an SPException. Just capture it and try again. Everything will work!

Leave a Reply

Name *
Email *
Website