Introduction

In this blog, we will learn about downloading all the files from a specific document library to our local machine and exporting all the metadata items in Excel.
Nuget Package Required:
  1. SharePointPnPCoreOnline
  2. Microsoft.Office.Interop.Excel
Required imports are:
  1. using System;
  2. using Microsoft.SharePoint.Client;
  3. using System.IO;
  4. using File = Microsoft.SharePoint.Client.File;
  5. using Excel = Microsoft.Office.Interop.Excel;
Authenticating with Sharepoint:
  1. string siteUrl = "Your Site Collection Url";
  2. string userName = "UserName of Account";
  3. string password = "Password";
  4. OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
  5. using (var clientContext= authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
The above code creates authentication with Sharepoint with a valid username and password. It returns a clientcontext object. With the clientcontext object, we will do our required operations in Sharepoint.
Creating an Excel file in a specified folder:
  1. var tempLocation = @"D:\files";
  2. // If directory does not exist, create it.
  3. if (!Directory.Exists(tempLocation))
  4. {
  5. Directory.CreateDirectory(tempLocation);
  6. }
  7. var filename = @"D:\files\myexfile.xlsx";
  8. FileInfo myfile = new FileInfo(filename);
  9. if (!myfile.Exists)
  10. {
  11. var wb = MyApp.Workbooks.Add();
  12. wb.SaveAs(@"D:\files\myexfile.xlsx");
  13. wb.Close();
  14. // FileStream fs = myfile.Create();
  15. }
The above code creates the blank excel file in the name of myexfile.aspx in the specified folder path
Code for downloading files to the local hard drive:
  1. var folderPath = "/Project Documents";
  2. var tempLocation = @"D:\files";
  3. FileCollection files = clientContext.Web.GetFolderByServerRelativeUrl(folderPath).Files;
  4. clientContext.Load(files);
  5. clientContext.ExecuteQuery();
  6. foreach (File file in files)
  7. {
  8. FileInformation fileInfo = File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
  9. clientContext.ExecuteQuery();
  10. // Console.WriteLine("File Name:: " + file.FieldValues["Title"]);
  11. var filePath = tempLocation + "\\" + file.Name;
  12. //var absoluteUrl = file.ListItemAllFields["FileRef"];
  13. using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
  14. {
  15. fileInfo.Stream.CopyTo(fileStream);
  16. }
  17. }
The above code downloads all files from the document library "Project Documents" to our local machin with the path "D:\files"
Code for exporting metadata to Excel:
  1. string listName = "Project Documents";
  2. // Retrieves list object using title
  3. List list = clientContext.Site.RootWeb.GetListByTitle(listName);
  4. if (list != null)
  5. {
  6. CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
  7. ListItemCollection items = list.GetItems(query);
  8. clientContext.Load(items);
  9. clientContext.ExecuteQuery();
  10. MyApp = new Excel.Application();
  11. MyApp.Visible = false;
  12. MyBook = MyApp.Workbooks.Open(@"D:\files\myexfile.xlsx");
  13. MySheet = (Excel.Worksheet)MyBook.Sheets[1]; // Explicit cast is not required here
  14. var lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
  15. var i = 1;
  16. foreach (ListItem listItem in items)
  17. {
  18. MySheet.Cells[i, 1].Value = listItem.FieldValues["ID"];
  19. MySheet.Cells[i,2].Value = listItem.FieldValues["FileLeafRef"];
  20. MySheet.Cells[i, 3].Value = listItem.FieldValues["Status"];
  21. i++;
  22. Console.WriteLine(listItem.FieldValues["ID"]);
  23. // We have all the list item data. For example, Title.
  24. }
  25. MyBook.Save();
  26. MyBook.Close();}
The above code will exports id, filename, status columns from the Sharepoint document library "Project Document "to Excel in the specified path @"D:\files\myexfile.xlsx"
Full Console Code:
  1. using System;
  2. using Microsoft.SharePoint.Client;
  3. using System.IO;
  4. using File = Microsoft.SharePoint.Client.File;
  5. using Excel = Microsoft.Office.Interop.Excel;
  6. namespace PnpCsom {
  7. class Program {
  8. static void Main(string[] args) {
  9. string siteUrl = "";
  10. string userName = "";
  11. string password = "";
  12. // Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
  13. Excel.Workbook MyBook = null;
  14. Excel.Application MyApp = null;
  15. Excel.Worksheet MySheet = null;
  16. // PnP component to set context
  17. OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
  18. try {
  19. // Get and set the client context
  20. // Connects to SharePoint online site using inputs provided
  21. using(var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password)) {
  22. var folderPath = "/Project Documents";
  23. var tempLocation = @ "D:\files";
  24. // If directory does not exist, create it.
  25. if (!Directory.Exists(tempLocation)) {
  26. Directory.CreateDirectory(tempLocation);
  27. }
  28. // List Name input
  29. string listName = "Project Documents";
  30. // Retrieves list object using title
  31. List list = clientContext.Site.RootWeb.GetListByTitle(listName);
  32. if (list != null) {
  33. CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
  34. ListItemCollection items = list.GetItems(query);
  35. clientContext.Load(items);
  36. clientContext.ExecuteQuery();
  37. MyApp = new Excel.Application();
  38. MyApp.Visible = false;
  39. var filename = @ "D:\files\myexfile.xlsx";
  40. FileInfo myfile = new FileInfo(filename);
  41. if (!myfile.Exists) {
  42. var wb = MyApp.Workbooks.Add();
  43. wb.SaveAs(@ "D:\files\myexfile.xlsx");
  44. wb.Close();
  45. // FileStream fs = myfile.Create();
  46. }
  47. MyBook = MyApp.Workbooks.Open(@ "D:\files\myexfile.xlsx");
  48. MySheet = (Excel.Worksheet) MyBook.Sheets[1]; // Explicit cast is not required here
  49. var lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
  50. var i = 1;
  51. foreach(ListItem listItem in items) {
  52. MySheet.Cells[i, 1].Value = listItem.FieldValues["ID"];
  53. MySheet.Cells[i, 2].Value = listItem.FieldValues["FileLeafRef"];
  54. MySheet.Cells[i, 3].Value = listItem.FieldValues["Status"];
  55. i++;
  56. Console.WriteLine(listItem.FieldValues["ID"]);
  57. // We have all the list item data. For example, Title.
  58. }
  59. MyBook.Save();
  60. MyBook.Close();
  61. // Displays required result
  62. Console.WriteLine("List Title : " + list.Title);
  63. FileCollection files = clientContext.Web.GetFolderByServerRelativeUrl(folderPath).Files;
  64. clientContext.Load(files);
  65. clientContext.ExecuteQuery();
  66. foreach(File file in files) {
  67. FileInformation fileInfo = File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
  68. clientContext.ExecuteQuery();
  69. // Console.WriteLine("File Name:: " + file.FieldValues["Title"]);
  70. var filePath = tempLocation + "\\" + file.Name;
  71. //var absoluteUrl = file.ListItemAllFields["FileRef"];
  72. using(var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create)) {
  73. fileInfo.Stream.CopyTo(fileStream);
  74. }
  75. }
  76. } else {
  77. Console.WriteLine("List is not available on the site");
  78. }
  79. Console.ReadKey();
  80. }
  81. } catch (Exception ex) {
  82. Console.WriteLine("Error Message: " + ex.Message);
  83. Console.ReadKey();
  84. }
  85. }
  86. }
  87. }

Conclusion

Hence, we learned about downloading all the files from a SharePoint document library using CSOM and also exporting metadata to Excel using CSOM. Hope this helps someone, Happy coding :)