3

I'm trying to copy over a publishing page across the Pages List from a source site-collection to a destination site-collection. All works well but when the control hits the context.ExecuteQuery() method, it gives me a ServerUnauthorizedAccess Exception.

The additional information being:

Access denied. You do not have permission to perform this action or access this resource.

sourceFile.CopyTo(desinationUrl, true);
ctx.ExecuteQuery();

The context mentioned above is the context in the source context. I'm passing in the credentials as follows:

ctx.Credentials = new SharePointOnlineCredentials("<userId>", <SecureStringPassword>);

Is there anything in additional that I'd have to configure anywhere?

  • here the client context for the destination site need to be created and used in the Ctx.ExecuteQuery() method – Esaki Dec 22 '16 at 6:28
0

CopyTo only works if you want to copy with the same site collection. If you want to copy across site collections, try below code:

public void CloneSitePages(string srcUrl, string srcLibrary, string destUrl, string userName, SecureString pwd)
{
string srclibraryname = string.Empty;
string fileName = string.Empty;
string folderPath = string.Empty;
int id = 0;
try
{
    ClientContext srcContext = new ClientContext(srcUrl);
    ClientContext destContext = new ClientContext(destUrl);
    srcContext.Credentials = new SharePointOnlineCredentials(userName, pwd);

    Web srcWeb = srcContext.Web;
    List srcList = srcWeb.Lists.GetByTitle("Pages");
    CamlQuery camlQuery = new CamlQuery();
    camlQuery.ViewXml = "<View Scope=’RecursiveAll’></View>";
    ListItemCollection itemColl = srcList.GetItems(camlQuery);
    srcContext.Load(itemColl);
    FieldCollection fields = srcList.Fields;
    srcContext.Load(fields);
    srcContext.ExecuteQuery();
    destContext.Credentials = new SharePointOnlineCredentials(userName, pwd);

    Web destWeb = destContext.Web;
    destContext.Load(destWeb);
    destContext.ExecuteQuery();
    string _path = destWeb.ServerRelativeUrl;
    if (itemColl.Count > 0)
    {
    srclibraryname = itemColl[0].FieldValues["FileDirRef"].ToString();
    string[] srcurlSplit = srclibraryname.Split('/');
    srclibraryname = srcurlSplit[srcurlSplit.Count()-1];
    foreach (ListItem doc in itemColl)
    {
        if (doc.FileSystemObjectType == FileSystemObjectType.File)
        {
            fileName = doc["FileRef"].ToString();
            string[] fileNames = fileName.Split(new string[] { srclibraryname }, StringSplitOptions.None);
            int lastRef = fileNames.Count()-1;
            fileName = fileNames[lastRef];
            Microsoft.SharePoint.Client.File file = doc.File;
            srcContext.Load(file);
            srcContext.ExecuteQuery();
            FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(srcContext, file.ServerRelativeUrl);
            string serverRelevantUrl = _path + "/" + srclibraryname + fileName;
            Microsoft.SharePoint.Client.File.SaveBinaryDirect(destContext, serverRelevantUrl, fileInfo.Stream, true);
            Microsoft.SharePoint.Client.File spfile = destContext.Web.GetFileByServerRelativeUrl(serverRelevantUrl);
            ListItem item = spfile.ListItemAllFields;
            destContext.Load(item);
            destContext.ExecuteQuery();
            id = item.Id;

            //update the properties to the current page
            List oList = destContext.Web.Lists.GetByTitle(srcLibrary);
            ListItem oListItem = oList.GetItemById(id);
            for (int i = 0; i < fields.Count; i++)
            {
            Field fieldTemp = fields[i];
            string InternalName = fieldTemp.InternalName;
                if ((!fieldTemp.ReadOnlyField) && (fieldTemp.InternalName != "Attachments") && (fieldTemp.InternalName != "ContentType"))
                {
                oListItem[InternalName] = doc[InternalName];
                }
            }
            oListItem.Update();
            destContext.ExecuteQuery();
            //Publish the page            
            oListItem.File.CheckIn("Migrated", CheckinType.MajorCheckIn);
            oListItem.File.Publish("Migrated");
            destContext.ExecuteQuery();

        }
        else if (doc.FileSystemObjectType == FileSystemObjectType.Folder)
        {
            folderPath = doc["FileRef"].ToString();
            string[] fileNames = folderPath.Split(new string[] { srclibraryname }, StringSplitOptions.None);
            int lastRef = fileNames.Count()-1;
            folderPath = fileNames[lastRef];
            folderPath = folderPath.TrimStart(new Char[] { '/' });
            var folder = CreateFolder(destContext.Web, srcLibrary, folderPath);
        }
        }
    }
}
catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

public Folder CreateFolder(Web web, string listTitle, string fullFolderPath)
{
if (string.IsNullOrEmpty(fullFolderPath))
    throw new ArgumentNullException("fullFolderPath");
    var list = web.Lists.GetByTitle(listTitle);
return CreateFolderInternal(web, list.RootFolder, fullFolderPath);

}
private Folder CreateFolderInternal(Web web, Folder parentFolder, string fullFolderPath)
{
    var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
    string folderUrl = folderUrls[0];
    var curFolder = parentFolder.Folders.Add(folderUrl);
    web.Context.Load(curFolder);
    web.Context.ExecuteQuery();
    if (folderUrls.Length > 1)
    {
    var folderPath = string.Join("/", folderUrls, 1, folderUrls.Count() – 1);
    return CreateFolderInternal(web, curFolder, folderPath);
    }
    return curFolder;
}

Reference - SPFile.CopyTo

Copy pages across site collection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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