Skip to content

Instantly share code, notes, and snippets.

@garima2510
Created October 31, 2014 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garima2510/6185a857fb851244b55a to your computer and use it in GitHub Desktop.
Save garima2510/6185a857fb851244b55a to your computer and use it in GitHub Desktop.
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