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#
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
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