Export (0) Print
Expand All

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 void Add(
	string leafName,
	byte[] data


Type: System.String

The name of the file to add.

Type: []

A byte array that contains the attachment.


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.

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.

© 2015 Microsoft