C# Sharepoint CSOM将文件复制到其他网站集
我想将文档从文档库复制到另一个网站集中的另一个文档库,并将所有附加的元数据一起从一个库复制到另一个库 我想在一个远程事件接收器中,用c#实现这一点 我的问题主要是:如何从这个开始?如果它在同一个网站集中,我可以在同一个上下文中将文档复制到新的库中,但我想我现在需要在不同的上下文中工作 这是我目前的代码:C# Sharepoint CSOM将文件复制到其他网站集,c#,sharepoint,csom,C#,Sharepoint,Csom,我想将文档从文档库复制到另一个网站集中的另一个文档库,并将所有附加的元数据一起从一个库复制到另一个库 我想在一个远程事件接收器中,用c#实现这一点 我的问题主要是:如何从这个开始?如果它在同一个网站集中,我可以在同一个上下文中将文档复制到新的库中,但我想我现在需要在不同的上下文中工作 这是我目前的代码: //Get current Item List curList = clientContext.Web.Lists.GetById(properties.Item
//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();
}
如果遇到类似情况,以下是我的解决方案供参考:
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);
}
使用文件信息也可以复制元数据 你必须为另一个站点创建一个单独的上下文并上传文件。如果能对你的代码如何工作做一点解释,那会很有帮助。