Guest User

Untitled

a guest
Jul 15th, 2019
78
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Program
  2. {
  3. static string url = "SiteURL";
  4. static string startPath = "Directory to the folder/devise where you want to save";
  5.  
  6. static void Main()
  7. {
  8. getFiles(url); //saves the files into the desired folder
  9. Console.WriteLine("nPress enter to close...");
  10. Console.Read();
  11. }
  12.  
  13. public static void getFiles(string url)
  14. {
  15. try
  16. {
  17. ClientContext ctx = new ClientContext(new Uri(@url));
  18.  
  19. List List = ctx.Web.Lists.GetByTitle("ListName");
  20. ctx.Load(List);
  21. ctx.Load(List.RootFolder);
  22. ctx.Load(List.RootFolder.Folders);
  23. ctx.Load(List.RootFolder.Files);
  24. ctx.ExecuteQuery();
  25.  
  26. FolderCollection fcol = List.RootFolder.Folders;
  27. foreach (Folder f in fcol)
  28. {
  29. ctx.Load(f.Files);
  30. ctx.ExecuteQuery();
  31. FileCollection fileCol = f.Files;
  32. foreach (File fileItem in fileCol)
  33. {
  34. //gets the full directory (startpath + directory inside sharepoint)
  35. var targetPath = startPath + System.IO.Path.GetDirectoryName(fileItem.ServerRelativeUrl);
  36.  
  37. if (!Directory.Exists(targetPath))
  38. {
  39. Directory.CreateDirectory(targetPath);
  40. }
  41.  
  42. //To download files/items inside list folders
  43. CopyFiles(fileItem, targetPath, url);
  44. }
  45. }
  46. }
  47.  
  48. catch (Exception ex)
  49. {
  50. Console.WriteLine(ex.Message);
  51. }
  52. }
  53.  
  54. private static void CopyFiles(File fileItem, string path, string url)
  55. {
  56. try
  57. {
  58. ClientContext ctx = new ClientContext(new Uri(@url));
  59. var fileRef = fileItem.ServerRelativeUrl;
  60. Console.WriteLine(fileRef);
  61. var fileName = System.IO.Path.GetFileName(fileRef);
  62. var fileInfo = File.OpenBinaryDirect(ctx, fileRef);
  63. var filePath = System.IO.Path.Combine(path, fileName);
  64. var fileStream = System.IO.File.Create(filePath);
  65. fileInfo.Stream.CopyTo(fileStream);
  66. fileStream.Close();
  67. }
  68.  
  69. catch (Exception ex)
  70. {
  71. Console.WriteLine(ex.Message);
  72. }
  73. }
  74. }
RAW Paste Data