Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ProviderHostedApp - CopyDocument
string filePath = "/TestLibrary/TestDocument.pptx";
var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
using (var sourceContext = spContext.CreateUserClientContextForSPHost())
{
Microsoft.SharePoint.Client.File sourceFile = sourceContext.Web.GetFileByServerRelativeUrl(filePath);
//file stream will be used to upload in destination library
var fileStream = sourceFile.OpenBinaryStream();
sourceContext.Load(sourceFile, k => k.ServerRelativeUrl, k => k.Name);
sourceContext.ExecuteQuery();
//generate destination context
string destinationSiteUrl = "url_of_destination_sharepoint_site"; //I used mysite url here
Uri destinationSiteUri = new Uri(destinationSiteUrl);
//target realm of the tenant (This is constant per tenant)
string targetRealm = TokenHelper.GetRealmFromTargetUrl(destinationSiteUri);
//generate access token for destination site
string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, destinationSiteUri.Authority, targetRealm).AccessToken;
//get destination site context using access token
using (var destinationContext = TokenHelper.GetClientContextWithAccessToken(destinationSiteUrl, accessToken))
{
//load server relative url of destination library
var destinationLibrary = destinationContext.Web.Lists.GetByTitle("DestinationLibrary");
FileCreationInformation fileCreationInfo = new FileCreationInformation();
fileCreationInfo.ContentStream = fileStream.Value;
fileCreationInfo.Url = sourceFile.Name;
fileCreationInfo.Overwrite = false;
Microsoft.SharePoint.Client.File destinationFile = destinationLibrary.RootFolder.Files.Add(fileCreationInfo);
destinationContext.Load(destinationFile, k => k.ServerRelativeUrl);
destinationContext.ExecuteQuery();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.