Wednesday, January 19, 2011

SharePoint 2010: read & write profile properties

Assuming the property exists and can be read and written, the following code does the job.

            StringBuilder s = new StringBuilder();

// get profile
SPServiceContext context = SPServiceContext.GetContext(SPContext.Current.Site);
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.Name);

// read & write profile's property
const string testProperty = "TestProperty";
string testValue;
UserProfileValueCollection val = profile[testProperty];
if (val != null && val.Value != null)
{
testValue = val.Value as string;
}
else
{
testValue = "Empty";
profile[testProperty].Value = DateTime.Now.ToString();
profile.Commit();
}
s.Append(profile[PropertyConstants.AccountName] + " = " + testValue);
s.Append(Environment.NewLine);
TestText.Text = s.ToString();

No comments: