Share via


SPFile.OpenBinary method

Opens the file in binary format.

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

Syntax

'Declaration
Public Function OpenBinary As Byte()
'Usage
Dim instance As SPFile
Dim returnValue As Byte()

returnValue = instance.OpenBinary()
public byte[] OpenBinary()

Return value

Type: []
A byte array that contains the file content.

Examples

The following code example iterates through the collection of files in the Shared Documents document library of the current site and opens each file in binary format so that it can be attached to a specified item in the Events list. The OpenBinary method fails if the size of the file is 0 (zero) bytes.

Dim web As SPWeb = SPContext.Current.Web
Dim attachFolder As SPFolder = web.Folders("Shared Documents")
Dim attachFiles As SPFileCollection = attachFolder.Files
Dim attachList As SPList = web.Lists("Events")
Dim attachItem As SPListItem = attachList.Items(10)
Dim attachments As SPAttachmentCollection = attachItem.Attachments
Dim attachFile As SPFile

For Each attachFile In  attachFiles

    Dim fileName As String = attachFile.Name
    Dim binFile As Byte() = attachFile.OpenBinary()

    attachments.Add(fileName, binFile)

Next attachFile
         
attachItem.Update()
SPWeb oWebsite = SPContext.Current.Web;
SPFolder oFolder = oWebsite.Folders["Shared Documents"];

SPFileCollection collFiles = oFolder.Files;
SPList oList = oWebsite.Lists["Events"];
SPListItem oListItem = oList.Items[10];
SPAttachmentCollection collAttachments = oListItem.Attachments;

foreach (SPFile oFile in collFiles)
{
    string strFilename = oFile.Name;
    byte[] binFile = oFile.OpenBinary();
    collAttachments.Add(strFilename, binFile);
}

oListItem.Update();

See also

Reference

SPFile class

SPFile members

OpenBinary overload

Microsoft.SharePoint namespace