SPAttachmentCollection class

Represents the collection of attachments for a list item.

System.Object
  Microsoft.SharePoint.SPAttachmentCollection

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

'Declaration
Public Class SPAttachmentCollection _
	Implements ICollection, IEnumerable
'Usage
Dim instance As SPAttachmentCollection

Use the Attachments property of the SPListItem class to return the collection of attachments for a list item. To create an attachment, use the Add method

Use an indexer to return the file name of a single attachment from the collection. For example, assuming the collection is assigned to a variable named collAttachments , use collAttachments[index] in C#, or collAttachments(index) in Visual Basic, where index is the index number of the attachment in the collection.

The following code example shows how to attach all the files from a Shared Documents document library to the first list item within a list that appears on every subsite under the site.

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

Dim oSiteCollection As SPSite = SPContext.Current.Site
Dim collWebsites As SPWebCollection = oSiteCollection.AllWebs

Dim oWebsite As SPWeb = collWebsites("Site_Name")
Dim oFolder As SPFolder = oWebsite.Folders("Shared Documents")

For Each oWebsiteNext As SPWeb In collWebsites
    Dim oList As SPList = oWebsiteNext.Lists("List_Name")
    Dim collItem As SPListItemCollection = oList.Items
    Dim oListItem As SPListItem = collItem(0)
    Dim collAttachments As SPAttachmentCollection = oListItem.Attachments

    Dim collFiles As SPFileCollection = oFolder.Files

    For Each oFile As SPFile In collFiles
        Dim strFileName As String = oFile.Name
        Dim binFile As Byte() = oFile.OpenBinary()
 
        collFiles.Add(strFileName, binFile)
    Next oFile

    oListItem.Update()
    oWebsiteNext.Dispose()
Next oWebsiteNext

oWebsite.Dispose()
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.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show: