How to programmatically list all SPS 2003 (or WSS v2.0) site groups and users they contain

This sample code demonstrates how to programmatically list all SharePoint Portal Server 2003 or Windows SharePoint Services v2.0 site groups and the users they contain (exception handling omitted). For simplicity the example code below demonstrates how to write this information to a basic text file.

In C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
 
StreamWriter Writer = File.CreateText(@"C:\Temp\GroupsAndUsers.txt");
 
try
{
  SPWeb PortalWeb = SPControl.GetContextWeb(Context);
  SPRoleCollection PortalGroups = PortalWeb.Roles;
 
  foreach(SPRole Group in PortalGroups)
  {
    Writer.WriteLine(String.Format("Group: {0}", Group.Name));
 
    foreach(SPUser User in Group.Users)
    {
      Writer.WriteLine(String.Format("- {0}", User.Name));
    }
  }
}
finally
{
  Writer.Close();
}

In VB.NET

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Imports System
Imports System.IO
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.WebControls
 
Dim Writer As StreamWriter = _
  File.CreateText("C:\Temp\GroupsAndUsers.Text")
 
Try
  Dim PortalWeb As SPWeb = SPControl.GetContextWeb(Context)
  Dim PortalGroups As SPRoleCollection = PortalWeb.Roles
 
  For Each Group As SPRole In PortalGroups
    Writer.WriteLine(String.Format("Group: {0}", Group.Name))
 
    For Each User As SPUser In Group.Users
      Writer.WriteLine(String.Format("- {0}", User.Name))
    Next
  Next
Finally
  Writer.Close()
End Try

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by WP-CopyRightPro