Recently I was tasked to create a console application to get all the attachments from a list and copy them to a file share. Everyone has code out there, but I noticed not one single place had the correct formatting for everything.
First off there is gotcha. You cannot copy SPAttachmentCollection from the List Item and step through the list of strings. You need to pull in the Item.Attachments.UrlPrefix and throw it into an SPFolder Item like below:
SPFolder Folder = Web.GetFolder(Item.Attachments.UrlPrefix);
If you try and pull out the File.OpenBinary(); without using this specific method for some reason you cannot grab the full SPFile. It is malformed.
So here is what it could look like if you wanted to get the attachments and copy them to the file share:
foreach(SPListItem Item in List.Items)
{
if(Item.Attachments.Count !=0)
{
SPFolder Folder = Web.GetFolder(Item.Attachments.UrlPrefix);
foreach(SPFile File in Folder)
{
byte[] CopyFile = File.OpenBinary(); //this fails if you pull in SPFile directly
//Your fstream code to copy file, remember to close your fstream when done
}
}
}
I hope that this helps someone else in the long run. Good luck. Catch you all later.