Wednesday, July 4, 2012

How to read SharePoint list items attachments programmatically?


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);
  }

2 comments: