Partilhar via


SPRoleCollection Class

NOTE: This API is now obsolete.

Use the new SPRoleDefinition and SPRoleAssignment classes instead, to define roles and to assign users to them. For more information, see Authorization Object Model. (In Windows SharePoint Services 2.0, SPRoleCollection represented a collection of SPRole objects and is maintained for backward compatibility.)

Inheritance Hierarchy

System.Object
  Microsoft.SharePoint.Administration.SPAutoSerializingObject
    Microsoft.SharePoint.SPBaseCollection
      Microsoft.SharePoint.SPRoleCollection

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: No

Syntax

'Declaration
<ObsoleteAttribute("Use the SPRoleDefinitionCollection class instead")> _
Public Class SPRoleCollection _
    Inherits SPBaseCollection
'Usage
Dim instance As SPRoleCollection
[ObsoleteAttribute("Use the SPRoleDefinitionCollection class instead")]
public class SPRoleCollection : SPBaseCollection

Remarks

Use the Roles property of the SPUser, SPGroup, or SPWeb class to return an SPRoleCollection object that represents the collection of roles for a user, group, or Web site. Use an indexer to return a single role from the collection. For example, if the collection is assigned to a variable named collRoles, use collRoles[index] in C#, or collRoles(index) in Visual Basic, where index is either the index number of the role in the collection or the display name of the site group.

Examples

The following code example adds all the users of a site to a specified role for all the subsites under the site.

Dim site As SPWeb = 
    SPContext.Current.Site.AllWebs("Site_Name")
Dim subSites As SPWebCollection = site.Webs
Dim users As SPUserCollection = site.Users
Dim user As SPUser

For Each user In  users

    Dim subSite As SPWeb

    For Each subSite In  subSites

        Dim role As SPRole = subSite.Roles("Role_Name")

        role.AddUser(user)

    Next subSite

Next user 
using(SPWeb oWebsite = SPContext.Current.Site.AllWebs["Site_Name"])
{
    SPWebCollection collWebsites = oWebsite.Webs;
    SPUserCollection collUsers = oWebsite.Users;

    foreach (SPUser oUser in collUsers)
    {
        foreach (SPWeb oWebsiteCurrent in collWebsites)
        {
            SPRole oRole = oWebsite.Roles["Role_Name"];
            oRole.AddUser(oUser);
            oWebsiteCurrent.Dispose();
        }
    }
}

Note

Certain objects implement the IDisposable interface, and you must avoid retaining these objects in memory after they are no longer needed. For information about good coding practices, see Disposing Objects.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SPRoleCollection Members

Microsoft.SharePoint Namespace