代码设置SPList权限(添加SPGroup)

 使用代码为SPList添加用户组,并且设置用户组的权限

 
代码实现 

using (SPSite mySPSite = new SPSite(<SPSiteURL>))

            {

                SPWeb mySPWeb = mySPSite.RootWeb;

                string spGroupName1 = "mySPGroup1";

                            //添加的用户必须是Domain中存在的用户

                string spUserName1 = "domain""user05";

                            //选择自定义权限级别,关于自定义权限级别的创建,

                   //可以参照鄙人的另一篇拙文http://www.cnblogs.com/Kenr/archive/2009/04/02/1428240.html

                string sitePermission1 = "完全控制";

                string sitePermission2 = "仅查看";

                            //SPSite里组和人员的作成

                SPMember siteOwner = (SPMember)mySPSite.Owner;

                mySPWeb.SiteGroups.Add(spGroupName1,siteOwner,null, string.Empty);

                mySPWeb.AllUsers.Add(spUserName1, "", "", "");

                           

                            ///开始对组的操作

                SPGroup mySPGroup1 = mySPWeb.SiteGroups[spGroupName1];

                            //往组里添加用户

                mySPGroup1.AddUser(mySPWeb.AllUsers[spUserName1]);

                            //在左边的导航栏中添加组的链接

                mySPWeb.AssociatedGroups.Add(mySPGroup1);

 

                            //为组添加权限

                SPRoleAssignment spRoleAssG1P1 = new SPRoleAssignment(mySPGroup1);

                SPRoleAssignment spRoleAssG1P2 = new SPRoleAssignment(mySPGroup1);

                spRoleAssG1P1.RoleDefinitionBindings.Add(mySPWeb.RoleDefinitions[sitePermission1]);

                spRoleAssG1P2.RoleDefinitionBindings.Add(mySPWeb.RoleDefinitions[sitePermission2]);

                            //为根网站添加带权限的组

                mySPWeb.RoleAssignments.Add(spRoleAssG1P1);

                            //为共享文档添加带权限的组

                            //必须先破坏继承关系才能为List添加新的权限

                mySPWeb.Lists["共享文档"].BreakRoleInheritance(false);

                mySPWeb.Lists["共享文档"].RoleAssignments.Add(spRoleAssG1P2);

                            //最后,不要忘记UPDATE

                mySPWeb.Update();

            }

posted on 2009-04-02 16:08  阿米巴原虫  阅读(665)  评论(0编辑  收藏  举报