User department not displaying when reading from user profile using C#

Frank Martin 431 Reputation points
2021-02-16T06:43:50.25+00:00

I am facing this issue where the following code is not working for one user (there may be more) i.e. Department field is coming as blank while for others it is working. If you see screenshots below, I am showing two users; user1 and user2 and for user1 it is working fine i.e. Department is being displayed but for user2 not Department is being displayed i.e. it is blank.

Code
using (SPSite site = new SPSite(SPContext.Current.Site.RootWeb.Url))
{
string userName = System.Web.HttpContext.Current.User.Identity.Name.Replace("0#.w|", "");
SPServiceContext context = SPServiceContext.GetContext(site);
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile currentUserProfile = profileManager.GetUserProfile(userName);
txtDepartment.Text = (string)currentUserProfile["department"].Value
//in above code txtDepartment.txt is coming as blank for user2 but for user1 it is showing dept name
}

User1 screenshot of User Profile Service
bXeWZ.jpg

User2 screenshot of User Profile Service
7Wmqy.jpg

SharePoint Server
SharePoint Server
A family of Microsoft on-premises document management and storage systems.
2,221 questions
SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,573 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Amos Wu-MSFT 4,051 Reputation points
    2021-02-17T06:35:09.973+00:00

    I recommend you to debug the above code to check if the userName is right.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.