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:
Download attachments from SharePoint list using C# Object model:
This code downloads all attachments from SharePoint list items.
//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();