Get user information out of SharePoint

There are different ways to get user information out of SharePoint. These examples describes how you can get that information by using some simple code.

  1. The user information is stored in a user field in a list (for example the Author field)

Dim query As String = "<Where><Eq><FieldRef Name=""ID"" /><Value Type=""Counter"">" & id & "</Value></Eq></Where>"
For Each listitem As SPListItem In Me.GetSPListItem(query)’custom method to get the items from the list
    If Not listitem.Fields(fieldname) Is Nothing Then

        Dim userField As SPFieldUser = listitem.Fields(fieldname)
        Dim userValue As SPFieldUserValue = userField.GetFieldValue(listitem(fieldname))
        If Not userValue Is Nothing Then
            Dim userObject As SPUser = userValue.User

        End If
    End If

Next

3 lines of code. First you get the SPFieldUser, then the SPFieldUserValue object en there is the SPUser object!

 

  1. The user information is not stored in a list but you have a user parameters (for example the emailaddress)

Using site As New SPSite(Me.siteUrl)
            Using website As SPWeb = site.OpenWeb()
                Dim userInfo As SPPrincipalInfo = Microsoft.SharePoint.Utilities.SPUtility.ResolvePrincipal(website, email, Utilities.SPPrincipalType.User, Utilities.SPPrincipalSource.UserInfoList, Nothing, True)
                If Not userInfo Is Nothing Then

                End If
                website.Close()
            End Using
            site.Close()
        End Using

In this example you use the SPPrincipalInfo object and the ResolvePrincipal method to get the information from the user. Using this method you can also retrieve information from groups.