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
)

Parameters

leafName
Type: System.String

The name of the file to add.

data
Type: []

A byte array that contains the attachment.

ExceptionCondition
ArgumentNullException

data is null .

SPException

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 = 
        oWebsite.Folders["Folder_Name"].Files["File_Name"];

    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);
    oListItem.Update();
}
NoteNote

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.

Show:
© 2015 Microsoft