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

2

6

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?

Tourney answered 26/8, 2009 at 13:28 Comment(0)
T
12
 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); 


        }
Tourney answered 26/8, 2009 at 13:55 Comment(0)
W
4

Maybe this will point you in a helpful direction:

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spattachmentcollection.aspx

also this might help

http://msdn.microsoft.com/en-us/library/lists.lists.addattachment.aspx

Weidman answered 26/8, 2009 at 13:42 Comment(1)
Thanks both those methods are too funky. I found another way to do itTourney

© 2022 - 2024 — McMap. All rights reserved.