How to copy users from Person and Group column from one site collection to another Site Collection

Copper Contributor

Hi,

I am facing some issue while copying multiple users from Person and Group column of a List from one site collection to another. Whether that users are present at target site or not, code not able to ensure users.So, how to copying them. Please help me.

My code which i have written:

 

static string LookupLoginNameInUserInfoList
(ClientContext context, int lookupId)
{
var username = string.Empty;

var userInfoList = context.Web.SiteUserInfoList;
context.Load(userInfoList);

ListItem item = userInfoList.GetItemById(lookupId);
context.Load(item);
context.ExecuteQuery();

string loginName = item["Name"] as string;
return loginName;
}

static void Main(string[] args)
{

                      FieldUserValue[] srcusers = (FieldUserValue[])item["Specialist"];
                      FieldUserValue[] usercollection = new FieldUserValue[srcusers.Length];

 

                          for (var i = 0; i < srcusers.Length; i++)
                            {                      
                        string loginName = LookupLoginNameInUserInfoList(ctx, srcusers[i].LookupId);

                        User newUser = web2.EnsureUser(loginName);
                        ctx2.Load(newUser);
                        ctx2.ExecuteQuery();

                        FieldUserValue[] users = (FieldUserValue[])item["Specialist"];
                        // construct the value of the people or group column for the user 
                        FieldUserValue newValue = new FieldUserValue();
                        newValue.LookupId = newUser.Id;

                        User user = web2.EnsureUser(loginName);
                        ctx2.Load(user);
                        ctx2.ExecuteQuery();
                        FieldUserValue fielduser = new FieldUserValue();
                        fielduser.LookupId = user.Id;
                        usercollection[i] = fielduser;
                        

                        targetListItem["Specialist"] = usercollection;
                    }
                        // write back to the target list 
                        targetListItem.Update();
                        ctx2.ExecuteQuery();

 }

Thanks

0 Replies