Here is a simple code sample for downloading SharePoint List Item attachments. When the code is run all attachments are downloaded. Subfolders are created based on the List Item ID.
Code Sample
using System.IO;
using Microsoft.SharePoint; //Located: C:\Program Files\Common Files\microsoft shared\web server extensions\12\ISAPI
...
static void Main(string[] args)
{
try
{
DownloadListAttachments(@"http://portalname/webname/", "listname", @"c:\Temp\Attachments\");
}
catch (Exception ex)
{
//TODO: Handle exception
}
}
public void DownloadListAttachments(string siteUrl, string listName,
string downloadLocation)
{
string downloadItemLocation = string.Empty;
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
foreach (SPFolder folder in
web.Folders["Lists"].SubFolders[listName].SubFolders["Attachments"].SubFolders)
{
foreach (SPFile file in folder.Files)
{
byte[] binFile = file.OpenBinary();
downloadItemLocation = downloadLocation + "\\" + folder.Name + "\\";
if (!Directory.Exists(downloadItemLocation))
{
Directory.CreateDirectory(downloadItemLocation);
}
System.IO.FileStream fstream =
System.IO.File.Create(downloadItemLocation + file.Name);
fstream.Write(binFile, 0, binFile.Length);
}
}
}
}
}
Screenshots
References
How to programmatically download attachments from list items in Windows SharePoint Services
Your post helped me. Thank you!!
ReplyDelete