I’ve been using this code for a while now, copying it from project to project as I needed it. I used it again today and thought I’d post it for anyone else out there that may be doing this for the first time.
Hand this method in a user’s account and the name of the profile property that you want to retrieve. Make sure you give it the actual property name, and not just the display name.
It will give you back the value of the property. If the property allows multiple values, this will hand them all back in a comma delimited string.
using Microsoft.Office.Server.UserProfiles;
private string GetProfileValueBrowser(string userID, string profileProperty)
{
string profileValue = string.Empty;
if (!string.IsNullOrEmpty(userID))
{
UserProfileManager profileManager = new UserProfileManager();
UserProfile userProfile = profileManager.GetUserProfile(userID);
UserProfileValueCollection profileValues = userProfile[profileProperty];
if (profileValues.Value != null)
{
string[] valueStrings = new string[profileValues.Count];
for (int i = 0; i < profileValues.Count; i++)
{
valueStrings[i] = Convert.ToString(profileValues[i]);
}
profileValue = string.Join(", ", valueStrings);
}
}
return profileValue;
}
Now, today I needed to do the same thing, but within a workflow’s code. The catch here is that you have no context and no user privileges. The updated method looks like this:
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
private string GetProfileValueWorkflow(string userID, string profileProperty)
{
string profileValue = string.Empty;
if (!string.IsNullOrEmpty(userID))
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
UserProfileManager profileManager = new UserProfileManager(ServerContext.Default);
UserProfile userProfile = profileManager.GetUserProfile(userID);
UserProfileValueCollection profileValues = userProfile[profileProperty];
if (profileValues.Value != null)
{
string[] valueStrings = new string[profileValues.Count];
for (int i = 0; i < profileValues.Count; i++)
{
valueStrings[i] = Convert.ToString(profileValues[i]);
}
profileValue = string.Join(", ", valueStrings);
}
});
}
return profileValue;
}
Hope it helps.
-Ryan