Get UserProfile Object of Logged-in User

In this article, I will explain how to get UserProfile object for Logged-in User (current user).
//Function Call
UserProfile objUserProfile= GetProfileOfCurrentUser(SPContext.Current.Web.CurrentUser.LoginName)
public UserProfile GetProfileOfCurrentUser(string accountName)
        {
            UserProfile profile = null;
            try
            {
                if (string.IsNullOrEmpty(accountName))
                {
                    return null;
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite site = SPContext.Current.Site;
                    ServerContext context = ServerContext.GetContext(site);

                    UserProfileManager profileManager = new UserProfileManager(context);
                    if (!profileManager.UserExists(accountName))
                    {
                        profile = null;
                    }

                    profile = profileManager.GetUserProfile(accountName);
                });
            }
            catch (Exception ex)
            {
                profile = null;
            }
            return profile;
        }

Post a Comment

Previous Post Next Post