Search This Blog

Wednesday, June 8, 2016

Retrieve Author of SPListItem as SPUser in SharePoint; programmatically (C#)

  public string GetListItemAuthorNameSPBuiltInFieldId(SPListItem spListItem)
      {
          string loginName = string.Empty;
          SPWeb spWeb = SPContext.Current.Web;

          var fullUserName = spListItem[SPBuiltInFieldId.Author] as string;
          var userName = fullUserName.Split('#')[1];//This is only to get the user name. My fullUserName was 1;#Setup Admin.
          SPUser spUser = spWeb.EnsureUser(userName);//You can get SPUser from here
          loginName = spUser.LoginName;
          return loginName;

      }

      public string GetListItemAuthorName(SPListItem spListItem)
      {
         string loginName = string.Empty;
         var spFieldUser = spListItem.Fields.GetFieldByInternalName("Author") as SPFieldUser;
   
         if (spFieldUser != null && spListItem["Author"] != null)
         {
            var fieldValue = spFieldUser.GetFieldValue(spListItem["Author"].ToString()) as SPFieldUserValue;
            if (fieldValue != null)
            {
               var spUser = fieldValue.User;//Get the SPUser
               loginName = spUser.LoginName;//Get the login name from SPUser
            }
         }
      return loginName;
      }

No comments:

Post a Comment