.NET King Logo Comments on: How to read SharePoint list items attachments programmatically?
Skip Navigation Links
Home
Weblog
How to... (video)
Articles
About us
Contact us
0 Items in Video cart!

How to read SharePoint list items attachments programmatically? (1/7/2009)

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


By: Jeff  
Thanks for the good example!
URL:  
By: Adnan  
thanks this really made my day awesome!!
URL:  
Your name:
Email:
URL:
Comments:
 

 -