Loop through SharePoint Profiles
written by on 02.04.2010 @ 12:54 pm in Programming, SharePoint 2007

Simple code sample showing how to retrieve profiles and their properties from a SharePoint site.


  • This code is relevant only if you’re running it on the SharePoint box, ie: web part, console app. If you need to access profiles outside of the box, use web services, as detailed by Michael Bowersox’s post.
  • Microsoft.Office.Server.UserProfiles reference.
  • Instantiate the UserProfileManager with your site context.
  • PropertyConstants for retrieval of pre-defined properties.  Every profile has a handful of standard properties, but check to make sure the property contains data to avoid a possible null reference exception.
  • Replace PropertyConstants with custom property name to get your custom properties.

using Microsoft.Office.Server.UserProfiles;

// Code Block for Profile Loop
using (SPSite site = new SPSite(spURL))
        // Get our context and the profile manager object
        ServerContext context = ServerContext.GetContext(site);
        UserProfileManager profileManager = new UserProfileManager(context);

        // Define our holder strings
        string firstName = string.Empty, lastName = string.Empty;
        string department = string.Empty, customProperty = string.Empty;

        // Loop through each user in the profile manager
        foreach (UserProfile user in profileManager)
            // grab the first and last name
            firstName = user[PropertyConstants.FirstName].Count > 0 ? user[PropertyConstants.FirstName].ToString() : string.Empty;
            lastName = user[PropertyConstants.LastName].Count > 0 ? user[PropertyConstants.LastName].ToString() : string.Empty;

            // grab the department
            department = user[PropertyConstants.Department].Count > 0 ? user[PropertyConstants.Department].ToString() : string.Empty;

            // grab a custom property
            customProperty = user["Custom Property Name"].Count > 0 ? user["Custom Property Name"].ToString() : string.Empty;
    catch (Exception ex)

Comment on this post

Name (required)

Email (required)



1 Comment so far
  1. Dilawar February 2, 2013 12:23 am

    Thanks for the post…..it really helpd me:)))))

© Copyright subtle detour. Powered by Wordpress. subtly taking you off course since 2009.