共用方式為


SPAttachmentCollection.Add method

新增附件所指定的檔案名稱和位元組陣列表示清單項目。

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

Syntax

'宣告
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: []

    位元組陣列,包含附件。

Exceptions

Exception Condition
ArgumentNullException

data是 null 。

SPException

檔案名稱已經存在於集合中。

備註

加入新的附件,使用這個方法會要求您更新使用Update方法的清單項目。

Examples

下列程式碼範例示範如何在 [佈告] 清單中新增檔案附件的項目。

由於Add方法需要您將檔案傳遞做為參數的二進位格式,範例會使用SPFile類別的OpenBinary方法來開啟資料夾內的每個檔案以二進位格式。

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();
}
注意事項注意事項

某些物件實作IDisposable介面,並且您必須避免之後不再需要保留這些物件在記憶體中。良好的程式碼撰寫方式的相關資訊,請參閱Disposing Objects

請參閱

參照

SPAttachmentCollection class

SPAttachmentCollection members

Microsoft.SharePoint namespace