Wednesday, May 05, 2010

Item Level Permission in a document Library

Here is how you can set item level permissions for a document library/list in sharepoint.





01 public string ItemLevelPermissions(string SiteAddress)

02

03 {

04

05 string ReturnResult = "";

06

07 try

08

09 {

10 SPSecurity.RunWithElevatedPrivileges(delegate()

11 {

12 using (SPSite WebApp = new SPSite(SiteAddressHere))

13 {

14

15 using (SPWeb Site = WebApp.OpenWeb())

16 {

17

18 SPList list = Site.Lists["MyDocLib"];

19

20 SPListItem item = list.Items[0];

21

22 SPRoleDefinition RoleDefinition = Site.RoleDefinitions.GetByType(SPRoleType.Contributor);

23

24 SPRoleAssignment RoleAssignment = new SPRoleAssignment("\\", "EmailAddressHere", "GiveNameHere", "GiveNotesHere");

25

26 RoleAssignment.RoleDefinitionBindings.Add(RoleDefinition);

27

28 if(!item.HasUniqueRoleAssignments)

29

30 {

31

32 item.BreakRoleInheritance(true);

33

34 }

35

36 item.RoleAssignments.Add(RoleAssignment);

37

38 item.Update();

39

40 }

41 }

42 });

43 }

44 catch (Exception ex)

45

46 {

47

48 ReturnResult += "Sorry the permissions could not be set for the item due to the following exception: " + ex.Message;

49

50 }

51

52 return ReturnResult;

53 }

No comments: