Sharepoint Online:使用客户端对象模型将列表项的附件复制到新项 [英] Sharepoint Online: Copy attachment of list item to a new item using Client object model

查看:98
本文介绍了Sharepoint Online:使用客户端对象模型将列表项的附件复制到新项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个列表项(在ItemCreated事件中)到另一个新的ListItem读取附件.如何使用客户端对象模型来做到这一点?我发现的只是服务器端代码...

I want to read the attachments from one list item (in ItemCreated event) to another, new ListItem. How can I do this with the Client Object Model? All I found is server-side code...

另一个问题:当我删除列表项时,附件也被删除了吗?还是服务器上仍然存在这些附件?

Another question: Are the attachments also deleted when I delete a list item or are they still existing on the server?

推荐答案

我明白了!以下代码对我有用:

I got it! The following code worked for me:

private static void NewTryToAttachFiles(ClientContext ctx, Web web, List fromList, ListItem fromItem, List toList, ListItem toItem)
    {
        string src = string.Format("{0}/lists/{1}/Attachments/{2}", web.Url, fromList.Title, fromItem.Id);

        Folder attachmentsFolder = web.GetFolderByServerRelativeUrl(src);
        web.Context.Load(attachmentsFolder);
        FileCollection attachments = attachmentsFolder.Files;

        web.Context.Load(attachments);
        web.Context.ExecuteQuery();

        if(attachments.Count > 0)
        {
            foreach (File attachment in attachments)
            {
                // FileInformation fileInfo = File.OpenBinaryDirect(ctx, attachment.ServerRelativeUrl);

                ctx.Load(toItem);
                var clientResultStream = attachment.OpenBinaryStream();
                ctx.ExecuteQuery();
                var stream = clientResultStream.Value;



                AttachmentCreationInformation attachFileInfo = new AttachmentCreationInformation();
                Byte[] buffer = new Byte[attachment.Length];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                System.IO.MemoryStream stream2 = new System.IO.MemoryStream(buffer);
                attachFileInfo.ContentStream = stream2;
                attachFileInfo.FileName = attachment.Name;

                Attachment a = toItem.AttachmentFiles.Add(attachFileInfo);
                ctx.Load(a);
                web.Context.ExecuteQuery();
                stream2.Close();
            }
        }
        ctx.Load(toItem);
        ctx.ExecuteQuery();
    }

它将一个列表项(fromItem)的附件复制到新项!

It copies the attachments of one list item (fromItem) to the new item!

这篇关于Sharepoint Online:使用客户端对象模型将列表项的附件复制到新项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆