Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c# - How to give an SPGroup permissions for an SPItem?

I tried to find a simple example how to give a certain Sharepoint group X, a permission level Y, for list item Z - but can't find example code.

The shortest code I could come up with for assigning a specific user permissions ("Reader" in this case) for the item is the following:

SPRoleDefinition spRole = spWeb.RoleDefinitions["Reader"];    
SPRoleAssignment roleAssignment= new SPRoleAssignment("//myDomain/myUser",
                                                      "[email protected]",
                                                      "Name", "Notes");    
roleAssignment.RoleDefinitionBindings.Add(spRole);

SPListItem listItem = spWeb.GetListItem("http://<URL to item somewhere on the Site>");
listItem.BreakRoleInheritance(true);
listItem.RoleAssegnments.Add(roleAssignment);
listItem.Update();

I know that SPRoleAssignment.Add can also take an SPPrincipal which in turn is a group - I just don't know how do write it.

Please give me some example code for how to add an existing Sharepoint group (e.g. "MyGroup") with the "Reader" permission level to my item.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually it was rather easy - instead of the SPRoleAssignment("user","name"...) I could just add an SPGroup to the role assignment and it worked! Full code following:

//note: using SiteGroups is "safer",
//because also groups which don't yet have any permissions are included
SPGroup spGroup = spWeb.SiteGroups["MyGroup"];
SPRoleDefinition spRole = spWeb.RoleDefinitions["Read"]; 

SPRoleAssignment roleAssignment= new SPRoleAssignment(spGroup);
roleAssignment.RoleDefinitionBindings.Add(spRole);

SPListItem listItem = spWeb.GetListItem("http://<URL to item somewhere on the Site>");
listItem.BreakRoleInheritance(true);
listItem.RoleAssignments.Add(roleAssignment);
listItem.Update();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...