SharePoint: How to add an attachment to a list item programatically?

JL. picture JL. · Aug 26, 2009 · Viewed 35.3k times · Source

I have the following code:

  SPList list = web.Lists[this.ListName];
  SPListItem item = list.Items.Add();

now what I want to do is:

   FileInfo[] attachments = attachmentDirectory.GetFiles();
        foreach (FileInfo attachment in attachments)
        {
           // Add the attachment from file system to the list item...

        }

How do I convert a normal file to a byte array?

Answer

JL. picture JL. · Aug 26, 2009
 foreach (FileInfo attachment in attachments)
        {
            FileStream fs = new FileStream(attachment.FullName , FileMode.Open,FileAccess.Read);

            // Create a byte array of file stream length
            byte[] ImageData = new byte[fs.Length];

            //Read block of bytes from stream into the byte array
            fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));

            //Close the File Stream
            fs.Close();

            item.Attachments.Add(attachment.Name, ImageData); 


        }