Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 291
JL. Avatar asked Aug 26 '09 13:08

JL.


People also ask

How do I add an attachment to a SharePoint List in power automate?

Click “New step”, search for “SharePoint” and select the “Add attachment” action. Set the “Site Address” and “List Name” to you target site and list. Set “Id” to “ID” from the previous “Create item” action. Set “File Name” to “name” from the “Parse JSON” action.

Can you attach files to a list item SharePoint?

You can also add an attachment to a list item—upload an image, or attach a file (such as a PDF, a photo, or a video from your device or from OneDrive or SharePoint).

How do I add an attachments column to a SharePoint list?

The attachment column is a default column in the Microsoft List, click on Add column > Show/hide columns > toggle on the Attachment. Then you will have the attachment field when create a new item in the list.

How do I enable attachments in a SharePoint list?

Anytime if you want to enable attachments in SharePoint Online list, in the SharePoint list advanced settings page, go to the Attachments section and select the Enabled radio button like below.


2 Answers

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

like image 29
swolff1978 Avatar answered Sep 21 '22 02:09

swolff1978


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


        }
like image 161
JL. Avatar answered Sep 22 '22 02:09

JL.