Here is the complete code:
class Program
{
static string url = "SiteURL";
static string startPath = "Directory to the folder/devise where you want to save";
static void Main()
{
getFiles(url); //saves the files into the desired folder
Console.WriteLine("\nPress enter to close...");
Console.Read();
}
public static void getFiles(string url)
{
try
{
ClientContext ctx = new ClientContext(new Uri(@url));
List List = ctx.Web.Lists.GetByTitle("ListName");
ctx.Load(List);
ctx.Load(List.RootFolder);
ctx.Load(List.RootFolder.Folders);
ctx.Load(List.RootFolder.Files);
ctx.ExecuteQuery();
FolderCollection fcol = List.RootFolder.Folders;
foreach (Folder f in fcol)
{
ctx.Load(f.Files);
ctx.ExecuteQuery();
FileCollection fileCol = f.Files;
foreach (File fileItem in fileCol)
{
//gets the full directory (startpath + directory inside sharepoint)
var targetPath = startPath + System.IO.Path.GetDirectoryName(fileItem.ServerRelativeUrl);
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
//To download files/items inside list folders
CopyFiles(fileItem, targetPath, url);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void CopyFiles(File fileItem, string path, string url)
{
try
{
ClientContext ctx = new ClientContext(new Uri(@url));
var fileRef = fileItem.ServerRelativeUrl;
Console.WriteLine(fileRef);
var fileName = System.IO.Path.GetFileName(fileRef);
var fileInfo = File.OpenBinaryDirect(ctx, fileRef);
var filePath = System.IO.Path.Combine(path, fileName);
var fileStream = System.IO.File.Create(filePath);
fileInfo.Stream.CopyTo(fileStream);
fileStream.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}