Loop through SharePoint Profiles
Simple code sample showing how to retrieve profiles and their properties from a SharePoint site.
Note:
- 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)) { try { // 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) { HandleException(ex); } }
Thanks for the post…..it really helpd me:)))))