Search This Blog

Tuesday, January 8, 2019

SharePoint 2013/2016 Download all attachments from SharePoint List- using Client Context(C#)


using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SharePointConsoleApps
{
    class Program
    {
static void Main(string[] args)
        {
ClientContext ctx = new ClientContext("http://sp2016:1234/sites/testSite/");
            //Retrieve list items attachments
            var list = ctx.Web.Lists.GetByTitle("testList");
            var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
            ctx.Load(items, icol => icol.Include(i => i["ID"], i => i.AttachmentFiles));
            ctx.ExecuteQuery();
            int count = 0;
            //attachment Urls for list items
            foreach (var item in items)
            {
                if (item.AttachmentFiles.Count > 0)
                {
                    Console.WriteLine("count" + count++);                 
                    foreach (var attachment in item.AttachmentFiles)
                    {
                        Console.WriteLine(attachment.ServerRelativeUrl);
                        FileInfo myFileinfo = new FileInfo(attachment.FileName);
                        using (WebClient client1 = new WebClient())
                        {
                            
                            client1.Headers["Accept"] = "/";
                            client1.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                            Uri uri = new Uri("http://sp2016:1234");
                            ICredentials credentials = CredentialCache.DefaultCredentials;
                            NetworkCredential credential = credentials.GetCredential(uri, "Basic");
                            client1.Credentials = credential;
                            client1.DownloadFile("http://sp2016:1234" + attachment.ServerRelativeUrl, @"D:/Jaison Arumugam/Downloads/" + attachment.FileName);
                            Console.WriteLine("Downloading " + attachment.ServerRelativeUrl);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("For {0} list item no attachments were found", item["ID"]);
                }
            }
}

}
}

No comments:

Post a Comment