Thursday, May 25, 2023

Get and download files from SharePoint Document library (desired folder) using CSOM

Sample code to read documents from desired folder in library and download locally to disk.
To work with C#(CSOM), use namespace (reference) Microsoft.SharePoint.Client.
static void Main(string[] args)
        {
            ClientContext cxt = new ClientContext("http://sp-test/sites/test");
            List list = cxt.Web.Lists.GetByTitle("Documents");
            cxt.Load(list);
            cxt.Load(list.RootFolder);
            cxt.Load(list.RootFolder.Folders);
            cxt.Load(list.RootFolder.Files);
            cxt.ExecuteQuery();
            FolderCollection folders = list.RootFolder.Folders;
            foreach (Folder folder in folders)
            {
                if ((folder.Name != "Forms")&(folder.Name == "Special Documents"))
                {
                    cxt.Load(folder.Files);
                    cxt.ExecuteQuery();
                    FileCollection fileCol = folder.Files;
                                      
                    foreach (Microsoft.SharePoint.Client.File file in fileCol)
                    {
                        string ServerRelativeUrl = file.ServerRelativeUrl;
                        DownloadFiles(ServerRelativeUrl);
                    }
                }
            }
        }
        public static void DownloadFiles(string ServerRelativeUrl)
        {
            ClientContext clientContext = new ClientContext("http://sp-test/sites/test");
            Web web = clientContext.Web;
            Microsoft.SharePoint.Client.File filetoDownload = web.GetFileByServerRelativeUrl(ServerRelativeUrl);
            clientContext.Load(filetoDownload);
            clientContext.ExecuteQuery();
            var fileRef = filetoDownload.ServerRelativeUrl;
            var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
            var fileName = Path.Combine(@"C:\Temp\Document", (string)filetoDownload.Name);

            using (var fileStream = System.IO.File.Create(fileName))
            {
                fileInfo.Stream.CopyTo(fileStream);
            }
        }

Happy Coding!

No comments:

Post a Comment