Sharepoint Online:使用客户端对象模型将列表项的附件复制到新项目
Sharepoint Online: Copy attachment of list item to a new item using Client object model
我想将附件从一个列表项(在 ItemCreated 事件中)读取到另一个新的 ListItem。如何使用 客户端对象模型 执行此操作?我找到的只是服务器端代码...
另一个问题:当我删除列表项时附件是否也被删除,还是它们仍然存在于服务器上?
我明白了!以下代码对我有用:
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) 的附件复制到新的项目中!
我想将附件从一个列表项(在 ItemCreated 事件中)读取到另一个新的 ListItem。如何使用 客户端对象模型 执行此操作?我找到的只是服务器端代码...
另一个问题:当我删除列表项时附件是否也被删除,还是它们仍然存在于服务器上?
我明白了!以下代码对我有用:
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) 的附件复制到新的项目中!