Search This Blog

Friday, August 16, 2019

SharePoint Client Context(c#) - Download Attachment to Drive Folder


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using SP = Microsoft.SharePoint.Client;
namespace SPFileDownload
{
    class Program
    {
        static string WebAppUrl = ConfigurationManager.AppSettings["WebAppUrl"];
        static string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
        static string ListName = ConfigurationManager.AppSettings["ListName"];
        static void Main(string[] args)
        {
            using (SP.ClientContext clientContext = new SP.ClientContext(siteUrl))
            {
                Console.WriteLine("Please enter download folder path (for ex: C:\\Downloads\\) ");
                Console.Write("Input :");
                string folderpath = Console.ReadLine();
                DownlaodAllAttachmentFromList(clientContext, ListName, folderpath);
            }
        }
        private static void DownlaodAllAttachmentFromList(SP.ClientContext clientContext, string eMSListName,string folderPath)
        {
          
            try
            {             

                using (clientContext)
                {
                    SP.List spList = clientContext.Web.Lists.GetByTitle(ListName);
                    clientContext.Load(spList);
                    clientContext.ExecuteQuery();
                    int count = 0;
                    if (spList != null && spList.ItemCount > 0)
                    {
                        SP.CamlQuery camlQuery = new SP.CamlQuery();                      
                        camlQuery.ViewXml = "<View Scope=\"RecursiveAll\"></View><Query><Where><Eq><FieldRef Name='Status' /><Value Type='Text'>Published</Value></Eq></Where><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy></Query>";
                        SP.ListItemCollection collListItem = spList.GetItems(camlQuery);
                        //SP.CamlQuery camlQuery = new SP.CamlQuery();
                        //camlQuery.ViewXml = "<View Scope=\"RecursiveAll\"></View>";
                        //SP.ListItemCollection collListItem = spList.GetItems(camlQuery);
                        clientContext.Load(collListItem);
                        clientContext.ExecuteQuery();
                        foreach (var item in collListItem)
                        {
                            if (Convert.ToString(item["Status"]) == "Published")
                            {                            
                                clientContext.Load(item.AttachmentFiles);
                                clientContext.ExecuteQuery();
                                if (item.AttachmentFiles.Count > 0)
                                {
                                    count = count + 1;
                                    foreach (var attachment in item.AttachmentFiles)
                                    {
                                       // DirectoryInfo dir = Directory.CreateDirectory(folderPath + item["ID"].ToString());
                                        DirectoryInfo dir = Directory.CreateDirectory(folderPath);
                                        FileInfo myFileinfo = new FileInfo(attachment.FileName);
                                        using (WebClient client1 = new WebClient())
                                        {
                                            client1.Headers["Accept"] = "/";
                                            client1.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                                            client1.UseDefaultCredentials = true;
                                         //   client1.DownloadFile(WebAppUrl + attachment.ServerRelativeUrl, folderPath + item["ID"].ToString() + "/" + attachment.FileName);
                                            client1.DownloadFile(WebAppUrl + attachment.ServerRelativeUrl, folderPath  + "/" + attachment.FileName);
                                            Console.WriteLine("Downloading " +count.ToString() +" : " + attachment.FileName);
                                        }
                                    }
                                  
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter log = new LogWriter("download failed." + ex.Message + ex.StackTrace);             
            }
         
        }
    }
}


No comments:

Post a Comment