See the following code snippet:
SPSite
mySite = new SPSite("http://sharepoinsiteaddress");
SPWeb myweb = mySite.OpenWeb();
SPList myList = myweb.Lists["Announcements"];
SPListItem myListItem =
myList.GetItemById(1);
foreach (String
attachmentname in myListItem.Attachments)
{
String attachmentAbsoluteURL =
myListItem.Attachments.UrlPrefix // gets the
containing directory URL
+ attachmentname;
// To get the SPSile reference to the attachment just
use this code
SPFile attachmentFile =
myweb.GetFile(attachmentAbsoluteURL);
// To read the file content simply use this code
Stream stream =
attachmentFile.OpenBinaryStream();
StreamReader reader =
new StreamReader(stream);
String fileContent = reader.ReadToEnd();
// assuming that file is a text attachment
MessageBox.Show(fileContent);
}
I think the code is self descriptive. Just some points to remember:
- Attachments collection of SPListItem object is not SPFile. It is string
that only represents file name.
- Most of the time just a hyperlink to the attachment serves the purpose
for the web UI design.
- I used a windows application to present this code, you may implement it
in any project.
- Don't forget the required namespaces.
-
using
System.IO;
-
using
Microsoft.SharePoint;
Enjoy!
Alireza