SharePoint 2010: "An error was encountered while retrieving the user profile"
Issue
An exception is thrown when retrieving a user profile:
Microsoft.Office.Server.UserProfiles.UserNotFoundException was unhandled
Message=An error was encountered while retrieving the user profile.
Source=Microsoft.Office.Server.UserProfiles
StackTrace:
at Microsoft.Office.Server.UserProfiles.UserProfileCache.GetUserData(UserProfileManager objManager, Nullable`1 recordId, Guid gAcct, String strAcct, Byte[] bSid, String strEmail, Boolean doNotResolveToMasterAccount)
at Microsoft.Office.Server.UserProfiles.UserProfile.RetrieveUser(String strAcct, Guid gAcct, Byte[] bSid, Nullable`1 recordId, Boolean doNotResolveToMasterAccount, Boolean loadFullProfile)
at Microsoft.Office.Server.UserProfiles.UserProfile..ctor(UserProfileManager objManager, String strAcct, Boolean doNotResolveToMasterAccount, Boolean forceUserIsSelf, Boolean loadFullProfile)
at Microsoft.Office.Server.UserProfiles.UserProfileManager.GetUserProfile(String strAccountName, Boolean doNotResolveToMasterAccount, Boolean loadFullProfile)
at Microsoft.Office.Server.UserProfiles.UserProfileManager.GetUserProfile(String strAccountName, Boolean doNotResolveToMasterAccount)
at Microsoft.Office.Server.UserProfiles.UserProfileManager.GetUserProfile(String strAccountName)
at WelcomeControlModification.Program.Main(String[] args)
This exception originates from the following line of code:
UserProfile userProfile = manager.GetUserProfile("Domain\userName");
Solution
After checking the domain and username are correct, as well as the permissions of the user executing the code, the exception is still thrown. Finally, notice the single backslash in the domain\username string. A single backslash (in a string) is often used for escape sequences. If you need to represent the character "\, then you need to escape it first, resulting in "\".
For example, the following command:
UserProfile userProfile = manager.GetUserProfile("Domain\userName");
becomes:
UserProfile userProfile = manager.GetUserProfile("Domain\\userName");
or it can also be written as:
UserProfile userProfile = manager.GetUserProfile(@"Domain\userName");