Quantcast
Channel: SharePoint Diary
Viewing all articles
Browse latest Browse all 1058

Download Attachments from SharePoint List Programmatically

$
0
0
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.

Viewing all articles
Browse latest Browse all 1058

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>