Proposed Understanding best way to get SPUser from login name string

  • Wednesday, August 08, 2012 9:28 AM
     
     

    Dear All,

    Just wanted to understand what is the best possible way to extract a SPUser object using Login Name in string format.

    I was using this till now:

    SPFieldUserValue spfUser = new SPFieldUserValue(spWeb, "<login name>");
    SPUser oUser = spfUser.User;

    Now, the 1st line fails with an exception "Value out of range" for a user who has READ through Visitor´s group and CONTRIBUTE through Member´s.

    So, I changed to this:

    SPUser oUser = spWeb.EnsureUser("<login name>");

    THis works perferctly fine.

    But what´s the problem with the 1st one?  And any negative impact due to the 2nd option?  And, is there any other better way to do this?

    Cheers,


    -- Sumit

All Replies

  • Wednesday, August 08, 2012 9:34 AM
     
     Proposed

    Hi Sumit,

    With first approach you mentioned, you will get an error if the user has never browsed the site (ie., there wont be ay entry for this user in the user information list)

    When you use EnsureUser() method, it checks if the user details are present in the user information list. If not, it will add them.

    So, it a good to use EnsureUser() method.


    Ram Prasad Meenavalli | MCTS SharePoint 2010 | MCPD SharePoint 2010

  • Wednesday, August 08, 2012 9:45 AM
     
     

    Thanks Ram, but that´s what is confusing me.

    The user (that is throwing the error) is using the site and in fact this error is thrown when the user is doing an action that has these lines in it´s code behind.

    I had cross checked, this person is there in the UserInfoList.

    Please advise.


    -- Sumit

  • Friday, August 24, 2012 8:32 AM
    Answerer
     
     

    Hello,

    maybe the user don't have the right to see the user "login name" , where is the "login name" user define? is it in a group that the current user can see the members? 


    Best regards, Christopher.
    Blog | Mail
    Please remember to click "Mark As Answer" if a post solves your problem or "Vote As Helpful" if it was useful.