Thursday, December 8, 2016

SharePoint 2013 Downloading a document library using C# and Microsoft.SharePoint.Client


using Microsoft.SharePoint.Client;
using Microsoft.SharePoint;
using SP = Microsoft.SharePoint.Client;
using System.IO;

Main program drive code
  • Gets a list of documents from a document library
  • Loops through the list of documents
  • Checks if there is more than one version of the document
  • Loops through the list of versions in a document library and calls downloadSharePointFile to download that version.

                        ListItemCollection collListItem = querySharePointList(list.Title);
                        foreach (ListItem oListItem in collListItem)
                            Console.WriteLine(string.Format("{0} - {1}", oListItem["FileLeafRef"], oListItem["FileRef"]));


                            //if (oListItem.File.Versions.Count > 1)
                                //MessageBox.Show("More than one version");

                            if (oListItem.File.Versions.Count > 1)
                                foreach (FileVersion version in oListItem.File.Versions)
                                    Console.WriteLine(String.Format("Version no: {0} url - {1}", version.VersionLabel, version.Url));
                                    downloadSharePointFile(version.Url, oListItem["FileLeafRef"].ToString());

                            //downloadSharePointFile(oListItem["FileRef"].ToString(), oListItem["FileLeafRef"].ToString());

Query the document library for a list of all the documents in the document library

title - the name of the document library

        private ListItemCollection querySharePointList(string title)
            SP.List oList = context2013.Web.Lists.GetByTitle(title);
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "5000";
            ListItemCollection collListItem = oList.GetItems(camlQuery);
            return collListItem;

Download the document from the document library

filename - url to the document
documentName - name of the document

        private void downloadSharePointFile(string filename, string documentName)
            string baseUri = "base url of the sharepoint application";
            // Create a new WebClient instance.
            WebClient myWebClient = new WebClient();
            System.Net.NetworkCredential netCredential = new System.Net.NetworkCredential("username", "password", "domain name");
            myWebClient.Credentials = netCredential;
            // Concatenate the domain with the Web resource filename.
            // Download the Web resource and save it into the current filesystem folder.
            string fileUrl = baseUri  + "/" + filename;
            myWebClient.DownloadFile(fileUrl, @"c:\temp\" + documentName);

No comments: