Question

I'm unable to get SPUsers/user.

As an example I have here a User (Approver):

<User ID=\"31\" Sid=\"\" Name=\"Approver\" LoginName=\"i:0#.w|domain\\approver\"
Email=\"approver@domain.se\" Notes=\"\" IsSiteAdmin=\"False\" 
IsDomainGroup=\"False\" Flags=\"0\" />

I've tried a variety of different ways to get the users:

SPUser user = web.SiteUsers.GetByID(31);
----------------------------------------------------------------------------------------    
SPUser user = web.Users.GetByID(31);
----------------------------------------------------------------------------------------
SPUser user = web.SiteUsers["LoginName"];
----------------------------------------------------------------------------------------
SPMember member = web.AllUsers["Domain\\User_Alias"]; 
----------------------------------------------------------------------------------------
SPUser user = web.EnsureUser("LoginName");

I run this with elevated privileges.

Still get the error: User cannot be found.

enter image description here

Any suggestions how to go about getting the SPUser Object. Or what can be of causing me not getting the users from the different methods above.

Was it helpful?

Solution

Try this

                SPUserCollection users=web.SiteUsers;
                SPUser user=users.GetByID(31);

SPweb.User return only users who are directly set as user on the web, if someone have access to web because he is in the particular group, this user cannot be found. SPweb.SiteUsers return all users

OTHER TIPS

Try any of the below:

  web.EnsureUser(@"domain\loginname");//This will add user to site if not already added.
                              //Best to use this if you have the login name and 
                              //user is already added.

  web.SiteUsers.GetByID(31);  //This will get you the user by id.

If you have the user's email address, give this method a try:

SPUser approver = web.SiteUsers.GetByEmail("approver@domain.se");

I suggest check it in PowerShell

$web = get-spweb $weburl;
$web.siteusers | ft UserLogin, Id;

Then try to get that specific user by id

$user = $web.siteusers.getbyid(31);
$user;

If this works in PowerShell, it should work in your managed code.

SPUser approver = web.SiteUsers.GetById(31);

NOTE: One thing to be aware of is that a users Id will change from one site collection to another.

I think you may be missing the following line:

web.AllowUnsafeUpdates = true; 

Since you are ensuring the user is part of the website and if not, it adds that user to the site, then you need to allow unsafeupdates. Your code should be:

web.AllowUnsafeUpdates = true; 
SPUser user = web.EnsureUser(@"Domain\LoginName");
//do more code stuff
web.AllowUnsafeUpdates = false;
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top