SPAttachmentCollection.Add method

Adds the attachment that is represented by the specified file name and byte array to the list item.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)


Public Sub Add ( _
    leafName As String, _
    data As Byte() _
Dim instance As SPAttachmentCollection
Dim leafName As String
Dim data As Byte()

instance.Add(leafName, data)
public void Add(
    string leafName,
    byte[] data


  • data
    Type: []

    A byte array that contains the attachment.


Exception Condition

data is null .


The file name already exists in the collection.


Adding a new attachment with this method requires that you update the list item using the Update method.


The following code example shows how to add a file attachment to an item in the Announcements list.

Since the Add method requires that you pass the file in binary format as a parameter, the example uses the OpenBinary method of the SPFile class to open each file within the folder in binary format.

Dim site As SPSite = SPContext.Current.Site
Dim srcSite As SPWeb = site.AllWebs("Site_Name")
Dim file As SPFile = srcSite.Folders("Folder_Name").Files("File_Name")
Dim list As SPList = srcSite.Lists("Announcements")

Dim listItem As SPListItem = list.Items(5)
Dim attachments As SPAttachmentCollection = listItem.Attachments

Dim fileName As String = file.Name
Dim binFile As Byte() = file.OpenBinary()

attachments.Add(fileName, binFile)

SPSite oSiteCollection = SPContext.Current.Site;
using(SPWeb oWebsite = oSiteCollection.AllWebs["Site_Name"])
    SPFile oFile = 

    SPList oList = oWebsite.Lists["Announcements"];
    SPListItem oListItem = oList.Items[5];

    SPAttachmentCollection collAttachments = oListItem.Attachments;

    string strFileName = oFile.Name;

    byte[] binFile = oFile.OpenBinary();
    collAttachments.Add(strFileName, binFile);


Certain objects implement the IDisposable interface, and you must avoid retaining these objects in memory after they are no longer needed. For information about good coding practices, see Disposing Objects.

See also


SPAttachmentCollection class

SPAttachmentCollection members

Microsoft.SharePoint namespace