共用方式為


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)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online

Syntax

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

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

Parameters

  • data
    Type: []

    A byte array that contains the attachment.

Exceptions

Exception Condition
ArgumentNullException

data is null .

SPException

The file name already exists in the collection.

Remarks

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

Examples

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)

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

Note

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

Reference

SPAttachmentCollection Class

SPAttachmentCollection Members

Microsoft.SharePoint Namespace