Karthik Murugesan Posted on October 23rd, 2013

Here is a sample code to download SharePoint list item attachments using Client Object Model. Getting the URL for each attachment is pretty straightforward. With CSOM you just need read access to the source SharePoint site and you don’t have to run this on the SharePoint server.

If you are working with a large list there are chances for the script to fail half way due to several reasons. So it is a good idea to get an input for the Start List ID and process only List Item ID greater than that value, this way when you run the script again you don’t have to start all over.


using Microsoft.SharePoint.Client;
using NLog;
using System;
using System.IO;
using System.Net;

namespace SiteActions.Task
{
  class Program
  {
  //You can get NLog from NuGet
  //http://www.nuget.org/packages/nlog
  private static Logger logger = LogManager.GetCurrentClassLogger();

  static void Main(string[] args)
  {
    try
    {
    int startListID;
    Console.WriteLine("Enter Starting List ID");
    if (!Int32.TryParse(Console.ReadLine(), out startListID))
    {
      Console.WriteLine("Invalid ID");
      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
      return;
    }

    String siteUrl = "http://siteaction.net/sites/teamsite";
    String listName = "SharePoint List Name";
    NetworkCredential credentials =
                new NetworkCredential("username", "password", "domain");

    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
       Console.WriteLine("Started Attachment Download " + siteUrl);
       logger.Info("Started Attachment Download" + siteUrl);
       clientContext.Credentials = credentials;

       //Get the Site Collection
       Site oSite = clientContext.Site;
       clientContext.Load(oSite);
       clientContext.ExecuteQuery();

       // Get the Web
       Web oWeb = clientContext.Web;
       clientContext.Load(oWeb);
       clientContext.ExecuteQuery();

       CamlQuery query = new CamlQuery();
       query.ViewXml = @"";

       List oList = clientContext.Web.Lists.GetByTitle(listName);
       clientContext.Load(oList);
       clientContext.ExecuteQuery();

       ListItemCollection items = oList.GetItems(query);
       clientContext.Load(items);
       clientContext.ExecuteQuery();

       foreach (ListItem listItem in items)
       {
          if (Int32.Parse(listItem["ID"].ToString()) >= startListID ){

          Console.WriteLine("Process Attachments for ID " +
                listItem["ID"].ToString());

          Folder folder =
                oWeb.GetFolderByServerRelativeUrl(oSite.Url +
                "/Lists/"+listName+/Attachments/" +
                listItem["ID"]);

          clientContext.Load(folder);

          try
          {
             clientContext.ExecuteQuery();
          }
          catch (ServerException ex)
          {
             logger.Info(ex.Message);
             Console.WriteLine(ex.Message);
             logger.Info("No Attachment for ID " + listItem["ID"].ToString());
             Console.WriteLine("No Attachment for ID " + listItem["ID"].ToString());
          }

          FileCollection attachments = folder.Files;
          clientContext.Load(attachments);
          clientContext.ExecuteQuery();

          foreach (Microsoft.SharePoint.Client.File oFile in folder.Files)
          {
             logger.Info("Found Attachment for ID " +
                   listItem["ID"].ToString());

             Console.WriteLine("Found Attachment for ID " +
                   listItem["ID"].ToString());

             FileInfo myFileinfo = new FileInfo(oFile.Name);
             WebClient client1 = new WebClient();
             client1.Credentials = credentials;

             logger.Info("Downloading " +
                   oFile.ServerRelativeUrl);

             Console.WriteLine("Downloading " +
                   oFile.ServerRelativeUrl);

             byte[] fileContents =
                   client1.DownloadData("http://siteaction.net" +
                   oFile.ServerRelativeUrl);

             FileStream fStream = new FileStream(@"C:Temp" +
                   oFile.Name, FileMode.Create);

             fStream.Write(fileContents, 0, fileContents.Length);
             fStream.Close();
          }
        }
      }
    }
    }
    catch (Exception e)
    {
      logger.ErrorException(e.Message, e);
      logger.Error(e.StackTrace);
      Console.WriteLine(e.Message);
      Console.WriteLine(e.StackTrace);
    }
    }
  }
}

(28287)

Comments

Ramiro December 6, 2013

Good Post.
Thanks.

Reply

 

LeeRoy Pitre July 21, 2014

I need to be able to download (export) SharePoint 2013 list “attachments” using MS Access 2013. I have linked to the list data. I can manually double click on the attachments object from with in MS Access to download the attachments. What object method or VBA coding can I use to download the attachments in my automated script? Seems like there should be a way via office integration, but I’m not finding it.

Thanks

Reply

 

http://ricardoalfonsinblog.com/profile-13588/info/ October 4, 2014

Cool blog! Is your theme custom made or did you download it from somewhere?
A theme like yours with a few simple adjustements would really make my blog jump out.
Please let me know where you got your design. Thanks

Reply

 

suresh T G March 17, 2015

Good one,its worked for me.

Reply

 

Leave a reply

Your email address will not be published.