BinaryStream.Open

From Xojo Documentation

Shared Method

BinaryStream.Open(f As FolderItem, readwrite As Boolean = False) As BinaryStream

New in 2009r3

Supported for all project types and targets.

Opens the passed FolderItem as a binary stream. The readwrite parameter controls whether the file is open for read/write operations or read-only. When True, you can read and write to the file. When False you can only read from the file. The default is False. If an error occurs, an IOException is raised.

Notes

Call Open using the syntax for a shared method.

Sample Code

This code reads a text file called "Whole File" and displays it in a TextArea. There is no attempt to parse the contents of the file.

Var f As New FolderItem("Whole File")
If f <> Nil Then
Try
Var bs As BinaryStream = BinaryStream.Open(f, False) // Open as read-only
// read the whole binaryStream
TextArea1.Value = bs.Read(bs.Length)

Catch e As IOException
// something went wrong when opening the file. This is where you would handle the error
// if appropriate
End Try
End If

This code reads each pair of bytes from a file and writes them in reverse order to a new file. The user chooses the source file using the Open-file dialog box and saves the new file using the Save as dialog box.

Var inputItem As FolderItem = FolderItem.ShowOpenFileDialog("")
If inputItem <> Nil Then
Var inputStream As BinaryStream = BinaryStream.Open(f, False)
Var outputItem As FolderItem = FolderItem.ShowSaveFileDialog("","")
If outputItem <> Nil Then
Try
Var outputStream As BinaryStream = BinaryStream.Create(f, True)
outputStream.LittleEndian = Not inputStream.LittleEndian
Do Until inputStream.EndOfFile
If inputStream.Length - inputStream.BytePosition >= 2 Then
outputStream.WriteUInt16(inputStream.ReadUInt16)
Else
outputStream.WriteByte(inputStream.ReadByte)
End If
Loop

Catch exc As IOException
MessageBox("Oops - failed to create the output file.")
End Try
End If
End If

Note: Create should here be called with overwrite=True because GetSaveFolderItem already asks the user for permission to do this (if the user doesn't want to overwrite an existing file, GetSaveFolderItem would return nil).