How to copy SPListitem from one SPList to Another SPList

后端 未结 4 1117
野的像风
野的像风 2021-01-25 09:39

I have requirement to copy items from one SPList to another,

Here is the code which is not working:

public void CopyList(SPList src)
{
    //Copy items f         


        
4条回答
  •  执念已碎
    2021-01-25 10:08

    You forgot to copy the item's attachments. Have a look at this article, part of the code has been repeated below.

    // ** Copy the fields
    foreach(SPField field in sourceItem.Fields)
    {
        if (newItem.Fields.ContainsField(field.InternalName) == true && 
            field.ReadOnlyField == false && field.InternalName != "Attachments")
        {
           newItem[field.InternalName] = sourceItem[field.InternalName];
        }
    }
    
    // ** Delete any existing attachments in the target item
    for (int i = newItem.Attachments.Count; i > 0; i-- )
    {
        newItem.Attachments.Delete(newItem.Attachments[i-1]);
    }
    
    // ** Copy any attachments
    foreach (string fileName in sourceItem.Attachments)
    {
        SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + 
                                                              fileName);
        byte[] imageData = file.OpenBinary();
        newItem.Attachments.Add(fileName, imageData);
    }
    
    // ** Remember where the original was copied from so we can update it in the future
    newItem["_M_CopySource"] = sourceItem["FileRef"];
    
    newItem.Update();
    

提交回复
热议问题