0

I need to move a file from one site collection to another with CSOM. There is a working sample here.

Move files with csom

When running the code I get an 401. It must be related to using modern authentication. Anyone knows how to do the same with modern auth?

var sourceSite = "https://xxx.sharepoint.com/sites/afd-286-oprydning-test-source";
var targetSIte = "https://xxx.sharepoint.com/sites/afd-286-oprydning-test-target";

var ctxSource = ClientContextExtension.GetAppContext(sourceSite, _config.AppRegistrationId, _config.AppRegistrationKey, "SaveToExcel", new EmptyLogger());
var ctxTarget = ClientContextExtension.GetAppContext(targetSIte, _config.AppRegistrationId, _config.AppRegistrationKey, "SaveToExcel", new EmptyLogger());

Web destWeb = ctxTarget.Web;
ctxTarget.Load(destWeb);
ctxTarget.ExecuteQuery();

Microsoft.SharePoint.Client.List list = ctxSource.Web.GetDocumentsList();
var item = list.GetItemById(1);
ctxSource.Load(item);
ctxSource.ExecuteQuery();

 if (item.FileSystemObjectType == FileSystemObjectType.File)
 {
     var file = item.File;
     ctxSource.Load(file);
     ctxSource.ExecuteQuery();

     var destLibrary = "Delte dokumenter";

     string location = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary + "/" + file.Name;
      var stream = file.OpenBinaryStream();
      ctxSource.ExecuteQuery();
      Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctxTarget, location, stream.Value, true);
 }

1 Answer 1

0

Found a solution:

var sourceSite = "https://xxx.sharepoint.com/sites/afd-xxx-oprydning-test-source";
var targetSIte = "https://xxx.sharepoint.com/sites/afd-xxx-oprydning-test-target";

var ctxSource = ClientContextExtension.GetAppContext(sourceSite, _config.AppRegistrationId, _config.AppRegistrationKey, "SaveToExcel", new EmptyLogger());
var ctxTarget = ClientContextExtension.GetAppContext(targetSIte, _config.AppRegistrationId, _config.AppRegistrationKey, "SaveToExcel", new EmptyLogger());
var targetLib = ctxTarget.Web.GetDocumentsList();

Microsoft.SharePoint.Client.List list = ctxSource.Web.GetDocumentsList();
var item = list.GetItemById(1);
ctxSource.Load(item);
ctxSource.ExecuteQuery();

if (item.FileSystemObjectType == FileSystemObjectType.File)
{
    var file = item.File;
    ctxSource.Load(file);          

    var stream = file.OpenBinaryStream();
    ctxSource.ExecuteQuery();

    string location = targetLib.RootFolder.ServerRelativeUrl.TrimEnd('/')+"/" + file.Name;               

    var fi = new FileCreationInformation();
    fi.ContentStream = stream.Value;
    fi.Url = location;
    fi.Overwrite = true;

    targetLib.RootFolder.Files.Add(fi);
    ctxTarget.ExecuteQuery();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.