Download Attachments from SharePoint List Programmatically

This code is a C# version of my earlier post: Download All Attachments from SharePoint List Items using PowerShell

Download attachments from SharePoint list using C# Object model:

//Variables
String SiteURL;
String ListName;
String downloadLocation;

//Get all inputs
Console.WriteLine("Enter the Site URL:");
SiteURL = Console.ReadLine();
Console.WriteLine("Enter the List Name:");
ListName = Console.ReadLine();
Console.WriteLine("Enter the Download Location:");
downloadLocation = Console.ReadLine();


using (SPSite oSPsite = new SPSite(SiteURL))
{
	using (SPWeb oSPWeb = oSPsite.OpenWeb())
	{
		oSPWeb.AllowUnsafeUpdates = true;

		//Get the List
		SPList list = oSPWeb.Lists[ListName];
		
		//Get all list items
		SPListItemCollection itemCollection = list.Items;

		//Loop through each list item
		foreach (SPListItem item in itemCollection)
		{
			string destinationFolder = downloadLocation + "\\" + item.ID;
			if (!Directory.Exists(destinationFolder))
			{
				Directory.CreateDirectory(destinationFolder);
			}

			//Get all attachments
			SPAttachmentCollection attachmentsColl = item.Attachments;
			
			//Loop through each attachment
			foreach (string attachment in attachmentsColl)
			{
				SPFile file = oSPWeb.GetFile(attachmentsColl.UrlPrefix + attachment);
				string filePath = destinationFolder + "\\" + attachment;

				byte[] binFile = file.OpenBinary();
				System.IO.FileStream fs = System.IO.File.Create(filePath);
				fs.Write(binFile, 0, binFile.Length);
				fs.Close();
			}

		}

	}
}
Console.WriteLine("Downloaded all attachments!");
//Pause
Console.ReadLine();

This code downloads all attachments from SharePoint list items.

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

Your email address will not be published. Required fields are marked *