I want to retrieve a SPUser
object by Login Name in C#.
In my program, I got a DataTable from the SPListItemCollection
and trying to get a SPUser Object in a foreach loop.
Here is the code snippet which shows how I am trying to get the SPUser
SPUser usera = new SPFieldUserValue(web, Convert.ToString(dr["OnlyUser"])).User;
but i got an error message about:
Value does not fall within the expected range
The error occurs because SPFieldUserValue
require a specific format ([int];#[domain]\[username])
. I failed because it returns the login name only from the DataTable.
Therefore, does anyone know how to get spuser obj by loginName without using SPWeb.EnsureUser()
because this will add user to site if not already added.
User information is stored in a list at the root site of a site collection. When you invoke
SPWeb.EnsureUser
it checks that list and adds the user to that list if they're not already there.You can access this list directly to check if someone already has an entry. The list can be accessed through the
SiteUserInfoList
property on theSPWeb
object.Note that the ID of a user's entry in the user info list is the number that appears before the
;#
in the string representation of a user.All that said, are you sure you need to avoid using
SPWeb.EnsureUser
? It adds the user to the information list if they don't have an entry in the list, but it does not automatically grant them access to the site, if that's what you're worried about.