我想从文档库中复制文档,其中包含所有附加的元数据,从一个库复制到另一个库中的另一个库。
我想在远程事件接收器中使用c#。
我的问题主要是:如何从这开始?如果它在同一个网站集中,我可以在同一个上下文中将文档复制到新库,但我想我现在需要在不同的上下文中工作?
这是我现在的代码:
//Get current Item
List curList = clientContext.Web.Lists.GetById(properties.ItemEventProperties.ListId);
ListItem curItem = curList.GetItemById(properties.ItemEventProperties.ListItemId);
clientContext.Load(curItem);
clientContext.ExecuteQuery();
string sNewSite = "url.toOtherSitecollection.com";
//Can we attempt contextception?
using (ClientContext siteCollContext = new ClientContext(sNewSite))
{
List destinationList = siteCollContext.Web.Lists.GetByTitle("DocumentLibrary_0001");
Folder destinationFolder = siteCollContext.Web.GetFolderByServerRelativeUrl("DocumentLibrary_0001");
FileCreationInformation newFileCreation = new FileCreationInformation { Content = Convert.FromBase64String(curItem.ToString()), Overwrite = true };
File newFile = destinationFolder.Files.Add(newFileCreation);
ListItem newItem = newFile.ListItemAllFields;
//Copy all the metadata as well.
try
{
newItem["..."] = curItem["..."];
//And all other metadata fields...
}
catch
{
//Log this.
}
newItem.Update();
siteCollContext.ExecuteQuery();
}
答案 0 :(得分:1)
有类似的情况,这是我的参考解决方案:
将新的FileCrationInformation添加到目标文件
static private void CopyFile()
{
ClientContext contextOrigin = new ClientContext(originSiteURL);
ClientContext contextDestination = new ClientContext(destinationSiteURL);
contextOrigin.Credentials = new SharePointOnlineCredentials(originUser, originSecurePassword);
contextDestination.Credentials = new SharePointOnlineCredentials(destinationUser, destinationSecurePassword);
//Grab File
FileInformation fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(contextOrigin, "/path/to/Document.docx"); //Server relative url
contextOrigin.ExecuteQuery();
//Read Stream
using (MemoryStream memoryStream = new MemoryStream())
{
CopyStream(fileInformation.Stream, memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
//Create Copy
var fileCreationInfo = new FileCreationInformation
{
ContentStream = memoryStream,
Overwrite = true,
Url = Path.Combine("path/to/", "CopiedDocument.docx")
};
var uploadFile = contextDestination.Web.RootFolder.Files.Add(fileCreationInfo);
contextDestination.Load(uploadFile);
contextDestination.ExecuteQuery();
}
}
static private void CopyStream(Stream source, Stream destination)
{
byte[] buffer = new byte[32768];
int bytesRead;
do
{
bytesRead = source.Read(buffer, 0, buffer.Length);
destination.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
使用FileInformation也可以复制元数据。