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 - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

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