I have a console application in which I am trying to move files from one folder to another folder in same document library using CSOM. While doing so I am getting below error:
(400) Bad Request
I have taken reference from this post
My code is as below:
using System;
using System.IO;
using System.Linq;
using System.Security;
using Microsoft.SharePoint.Client;
using ClientOM = Microsoft.SharePoint.Client;
namespace ConsoleApp2
{
public static class FolderExtensions
{
public static void MoveFilesTo(this Folder folder, string folderUrl)
{
var ctx = (ClientContext)folder.Context;
//SecureString passWord = new SecureString();
//foreach (char c in "HelloWorld@1234".ToCharArray()) passWord.AppendChar(c);
//ctx.Credentials = new SharePointOnlineCredentials("[email protected]", passWord);
if (!ctx.Web.IsPropertyAvailable("https://company.sharepoint.com"))
{
ctx.Load(ctx.Web, w => w.ServerRelativeUrl);
}
ctx.Load(folder, f => f.Files, f => f.ServerRelativeUrl, f => f.Folders);
ctx.ExecuteQuery();
//Ensure target folder exists
//ctx.Web.EnsureFolder(folderUrl.Replace(ctx.Web.ServerRelativeUrl, string.Empty));
foreach (var file in folder.Files)
{
var targetFileUrl = file.ServerRelativeUrl.Replace(folder.ServerRelativeUrl, folderUrl);
file.MoveTo(targetFileUrl, MoveOperations.Overwrite);
}
ctx.ExecuteQuery();
}
}
//static class WebExtensions
//{
// /// <summary>
// /// Ensures whether the folder exists
// /// </summary>
// /// <param name="web"></param>
// /// <param name="folderUrl"></param>
// /// <returns></returns>
// public static Folder EnsureFolder(this Web web, string folderUrl)
// {
// return EnsureFolderInternal(web.RootFolder, folderUrl);
// }
// private static Folder EnsureFolderInternal(Folder parentFolder, string folderUrl)
// {
// var ctx = parentFolder.Context;
// var folderNames = folderUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
// var folderName = folderNames[0];
// var folder = parentFolder.Folders.Add(folderName);
// ctx.Load(folder);
// ctx.ExecuteQuery();
// if (folderNames.Length > 1)
// {
// var subFolderUrl = string.Join("/", folderNames, 1, folderNames.Length - 1);
// return EnsureFolderInternal(folder, subFolderUrl);
// }
// return folder;
// }
//}
class Program
{
static void Main(string[] args)
{
var srcFolderUrl = "/sites/DataServices/Shared Documents/Data Dictionaries";
var destFolderUrl = "/sites/DataServices/Shared Documents/Data Dictionaries/Archive";
using (var ctx = new ClientContext("https://companyname.sharepoint.com"))
{
var sourceFolder = ctx.Web.GetFolderByServerRelativeUrl(srcFolderUrl);
sourceFolder.MoveFilesTo(destFolderUrl);
ctx.ExecuteQuery();
}
}
}
}