Tell me more ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I'd like to know how can I do to access to Active Directory information (eg: Department) of an User starting from an SPUser... I've User Profile Service configured and I see in Sharepoint those fields..

Thank you!

share|improve this question

2 Answers

up vote 3 down vote accepted

You also can use the SPUser and SPUserCollection Object to iterate through all user profiles

using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using System.Web;

here is the code:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
                using (SPSite siteCollection = new SPSite("http://testssite:1130"))
                {
                    using (SPWeb site = siteCollection.OpenWeb())
                    {
                        ServerContext serverContext = ServerContext.GetContext(siteCollection);
                        UserProfileManager userProfileMangager = new UserProfileManager(serverContext);
                        SPUserCollection userCollection = site.AllUsers;
                        foreach (SPUser spUser in userCollection)
                        {
                           UserProfile profile = userProfileMangager.GetUserProfile(spUser.LoginName);    
                           Console.WriteLine(profile["department"].Value);    




                    }
                }
            });
share|improve this answer
3  
The RunWithElevatedPrivileges call will works only of the system account is declared as administrator on the profile service application. Don't forget to grant this role, if you don't want to get obscure NullReferenceException – Steve B Jun 18 '12 at 14:37

You will need to load it from the User Profiles and not the SPUser object.

SPServiceContext svcContext = SPServiceContext.GetContext(site);
UserProfileManager profileManager = new UserProfileManager(svcContext);
UserProfile profile = profileManager.GetUserProfile(accountname);
string department = profile["department"].Value;
share|improve this answer
2  
beware, you should run this code with a user with privileges on the profile application service. Even a elevated code with RunWithElevatedPermission won't be enough. – Steve B Jun 18 '12 at 14:36
1  
If you are simply reading from the user profiles all users should have access to read without the need to elevate privileges. – Mike Oryszak Jun 18 '12 at 14:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.