I want to give read only permission programatically to specific user whenever a new site is created
2 Answers
You can grant a user read only access to a site using the following PowerShell. If you're creating the site using PowerShell, tag it onto the end of your script. If you're creating the site through the SharePoint GUI you can run the script from the SharePoint Management Shell afterwards.
Set-SPUser -Identity 'domain\user_name' -Web http://yourNewSite/site -AddPermissionLevel Read
[Edit]
If your site collection already exists and you're creating a new subsite within it, you can write en event receiver based on WebProvisioned and grant the particular user access using SPRoleAssignment.
I'm assuming this is either SP 2010 or 2013 on-premise.
You can create an EventReceiver
with Visual Studio to listen to the WebProvisioned
event, and in this event you give read-only permissions to a user or group etc.
Your code in the WebProvisioned
EventReceiver
could look something like this:
public override void WebProvisioned(SPWebEventProperties properties)
{
base.WebProvisioned(properties);
var web = properties.Web;
web.AllowUnsafeUpdates = true;
web.BreakRoleInheritance(true);
// Insert logic here to find specific user or group...
// Example
var user = web.EnsureUser("domain\username");
var roleDefinition = web.RoleDefinitions["Read"];
var roleAssignment = new SPRoleAssignment(user);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
web.RoleAssignments.Add(roleAssignment);
web.AllowUnsafeUpdates = false;
web.Update();
}
-
I am facing error like "Permission level doesnt exist". Can you tell me solution for it– DRSMay 21, 2015 at 14:32