BinaryStream.Create

From Xojo Documentation

Shared Method

BinaryStream.Create(f As FolderItem, overwrite As Boolean) As BinaryStream

New in 2009r3

Supported for all project types and targets.

Creates a file and opens a binary stream for reading and exclusive writing to the passed FolderItem.

Notes

The overwrite parameter controls whether the operation can overwrite an existing file. The default is False.

Invoke Create using the syntax for shared methods, i.e. use BinaryStream.Create(...)

If the stream can not be opened as requested, an IOException will be raised. For instance, this will happen if the file is already opened for writing, or if the app (its user) has no permission to modify this file or to create a file in the affected directory.

Sample Code

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).