Table of Contents

CompoundStream Class

Definition

Namespace
Bodu.IO.Compound
Assembly
Bodu.IO.Compound.dll
Package
Bodu.IO.Compound 1.0.0
Source
CompoundStream.cs

Provides seekable access to the bytes of a single stream within a compound file.

public sealed class CompoundStream : Stream, IAsyncDisposable, IDisposable
Inheritance
CompoundStream
Implements
Inherited Members
Extension Methods

Examples

The following example opens a compound file, navigates to a named stream, and reads its leading bytes through the cursor.

using Bodu.IO.Compound;

using CompoundFile file = CompoundFile.Open(File.OpenRead("book.xls"));
using CompoundStream stream = file.RootStorage.OpenStream("Workbook");
byte[] signature = new byte[8];
stream.ReadExactly(signature);

// Seek back to the start and hand the cursor to any Stream consumer.
stream.Seek(0, SeekOrigin.Begin);
using var reader = new BinaryReader(stream);
ushort recordType = reader.ReadUInt16();

Remarks

CompoundStorage.OpenStream returns a CompoundStream, a read-only seekable Stream cursor whose CanWrite is false. When the owning CompoundFile was opened buffered (the default), the stream's whole payload is materialized into an in-memory byte array at open time and Read, Seek, and AsMemory work over that array. When the file was opened with buffered false, the cursor walks the stream's sector chain in the source on demand: each Read locates the sector for the current Position, copies only the bytes within that sector, and advances, so the full payload is never held in memory. AsMemory materializes the whole chain on request.

CompoundStream is a standard Stream cursor obtained from OpenStream(string), so it composes with the BCL surfaces that consume a Stream - StreamReader, BinaryReader, CopyTo(Stream), and the deserializers built on top of them.

A stream opened from a buffered compound file is backed by an in-memory payload assembled at open time. A stream opened from a streaming compound file (see Open(Stream, bool, bool) with buffered: false) reads its sectors on demand from the underlying source, so it never materializes the whole payload. In the streaming case the owning CompoundFile and its source must remain open for the lifetime of the cursor.

A stream opened from a writable compound file (see Create(Stream, bool, CompoundBuildOptions)) is backed by a growable in-memory buffer: CanWrite is true, and Write(byte[], int, int) and SetLength(long) mutate the buffer. The edits are staged in memory and are persisted to the underlying destination only when Commit() is called; closing the cursor flushes its buffer into the staging tree but does not write to the destination. A writable cursor holds at most MaxValue bytes - payloads beyond that are authored through the deferred stream sources on CompoundStorageBuilder (AddStream(name, openRead, length) or AddStreamFromFile), which never buffer the whole payload.

A read-only cursor (CanWrite is false) throws NotSupportedException from Write(byte[], int, int) and SetLength(long). Because reads against a streaming source advance a shared position, a single cursor is not safe for concurrent use; open one cursor per reader.

Properties

CanRead

When overridden in a derived class, gets a value indicating whether the current stream supports reading.

public override bool CanRead { get; }

Property Value

bool

true if the stream supports reading; otherwise, false.

CanSeek

When overridden in a derived class, gets a value indicating whether the current stream supports seeking.

public override bool CanSeek { get; }

Property Value

bool

true if the stream supports seeking; otherwise, false.

CanWrite

When overridden in a derived class, gets a value indicating whether the current stream supports writing.

public override bool CanWrite { get; }

Property Value

bool

true if the stream supports writing; otherwise, false.

Length

When overridden in a derived class, gets the length in bytes of the stream.

public override long Length { get; }

Property Value

long

A long value representing the length of the stream in bytes.

Exceptions

NotSupportedException

A class derived from Stream does not support seeking and the length is unknown.

ObjectDisposedException

Methods were called after the stream was closed.

ObjectDisposedException

Thrown when the cursor has been disposed.

Name

Gets the directory name of the stream.

public string Name { get; }

Property Value

string

The stream name as stored in the compound-file directory.

Parent

Gets the storage that owns this stream cursor.

public CompoundStorage? Parent { get; }

Property Value

CompoundStorage

The owning CompoundStorage, or null when not available.

Position

When overridden in a derived class, gets or sets the position within the current stream.

public override long Position { get; set; }

Property Value

long

The current position within the stream.

Exceptions

IOException

An I/O error occurs.

NotSupportedException

The stream does not support seeking.

ObjectDisposedException

Methods were called after the stream was closed.

ArgumentOutOfRangeException

Thrown on set when the value is negative.

ObjectDisposedException

Thrown when the cursor has been disposed.

Stat

Gets the metadata snapshot for this stream entry.

public CompoundEntryInfo Stat { get; }

Property Value

CompoundEntryInfo

A CompoundEntryInfo describing the stream's name, size, class id, and timestamps.

Methods

AsMemory()

Returns a read-only view over the entire stream payload, materializing it for an on-demand stream.

public ReadOnlyMemory<byte> AsMemory()

Returns

ReadOnlyMemory<byte>

A ReadOnlyMemory<T> spanning the payload bytes.

Examples

using CompoundStream stream = storage.OpenStream("Workbook");
ReadOnlyMemory<byte> payload = stream.AsMemory();
ushort recordType = BinaryPrimitives.ReadUInt16LittleEndian(payload.Span);

Remarks

For a buffered stream this returns a view over the already-materialized payload without copying; for a streaming stream it reads the whole payload into memory; for a writable stream it returns the bytes written so far. The returned view does not advance or depend on Position. Prefer chunked Read(Span<byte>) for large streaming payloads.

Dispose(bool)

Releases the unmanaged resources used by the Stream and optionally releases the managed resources.

protected override void Dispose(bool disposing)

Parameters

disposing bool

true to release both managed and unmanaged resources; false to release only unmanaged resources.

Flush()

When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.

public override void Flush()

Remarks

For a writable cursor this flushes the buffered bytes into the staging tree and marks the owning file dirty; the destination is written only by Commit(). For a read-only cursor this is a no-op.

Exceptions

IOException

An I/O error occurs.

ObjectDisposedException

Thrown when the cursor has been disposed.

FlushAsync(CancellationToken)

Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

public override Task FlushAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

The token to monitor for cancellation requests. The default value is None.

Returns

Task

A task that represents the asynchronous flush operation.

Exceptions

ObjectDisposedException

The stream has been disposed.

OperationCanceledException

The cancellation token was canceled. This exception is stored into the returned task.

Read(byte[], int, int)

When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

public override int Read(byte[] buffer, int offset, int count)

Parameters

buffer byte[]

An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.

offset int

The zero-based byte offset in buffer at which to begin storing the data read from the current stream.

count int

The maximum number of bytes to be read from the current stream.

Returns

int

The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if count is 0 or the end of the stream has been reached.

Exceptions

ArgumentException

The sum of offset and count is larger than the buffer length.

ArgumentNullException

buffer is null.

ArgumentOutOfRangeException

offset or count is negative.

IOException

An I/O error occurs.

NotSupportedException

The stream does not support reading.

ObjectDisposedException

Methods were called after the stream was closed.

Read(Span<byte>)

When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

public override int Read(Span<byte> buffer)

Parameters

buffer Span<byte>

A region of memory. When this method returns, the contents of this region are replaced by the bytes read from the current source.

Returns

int

The total number of bytes read into the buffer. This can be less than the size of the buffer if that many bytes are not currently available, or zero (0) if the buffer's length is zero or the end of the stream has been reached.

Exceptions

NotSupportedException

Thrown when the cursor is write-only.

ObjectDisposedException

Thrown when the cursor has been disposed.

ReadAllBytes()

Copies the entire stream payload into a new byte array, independent of the current position.

public byte[] ReadAllBytes()

Returns

byte[]

A byte array containing the whole payload.

Remarks

Mirrors File.ReadAllBytes for callers that consume the whole stream in one pass. Prefer AsMemory() when a zero-copy view suffices, or chunked Read(Span<byte>) for large streaming payloads.

ReadAsync(byte[], int, int, CancellationToken)

Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)

Parameters

buffer byte[]

The buffer to write the data into.

offset int

The byte offset in buffer at which to begin writing data from the stream.

count int

The maximum number of bytes to read.

cancellationToken CancellationToken

The token to monitor for cancellation requests. The default value is None.

Returns

Task<int>

A task that represents the asynchronous read operation. The value of the TResult parameter contains the total number of bytes read into the buffer. The result value can be less than the number of bytes requested if the number of bytes currently available is less than the requested number, or it can be 0 (zero) if count is 0 or if the end of the stream has been reached.

Exceptions

ArgumentNullException

buffer is null.

ArgumentOutOfRangeException

offset or count is negative.

ArgumentException

The sum of offset and count is larger than the buffer length.

NotSupportedException

The stream does not support reading.

ObjectDisposedException

The stream has been disposed.

InvalidOperationException

The stream is currently in use by a previous read operation.

OperationCanceledException

The cancellation token was canceled. This exception is stored into the returned task.

ReadAsync(Memory<byte>, CancellationToken)

Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)

Parameters

buffer Memory<byte>

The region of memory to write the data into.

cancellationToken CancellationToken

The token to monitor for cancellation requests. The default value is None.

Returns

ValueTask<int>

A task that represents the asynchronous read operation. The value of its Result property contains the total number of bytes read into the buffer. The result value can be less than the length of the buffer if that many bytes are not currently available, or it can be 0 (zero) if the length of the buffer is 0 or if the end of the stream has been reached.

Remarks

This is truly asynchronous only for a streaming-mode cursor, which reads its sectors on demand from the underlying source; a buffered or writable cursor reads from memory and completes synchronously.

Exceptions

OperationCanceledException

The cancellation token was canceled. This exception is stored into the returned task.

Seek(long, SeekOrigin)

When overridden in a derived class, sets the position within the current stream.

public override long Seek(long offset, SeekOrigin origin)

Parameters

offset long

A byte offset relative to the origin parameter.

origin SeekOrigin

A value of type SeekOrigin indicating the reference point used to obtain the new position.

Returns

long

The new position within the current stream.

Exceptions

IOException

An I/O error occurs.

NotSupportedException

The stream does not support seeking, such as if the stream is constructed from a pipe or console output.

ObjectDisposedException

Methods were called after the stream was closed.

ObjectDisposedException

Thrown when the cursor has been disposed.

SetLength(long)

When overridden in a derived class, sets the length of the current stream.

public override void SetLength(long value)

Parameters

value long

The desired length of the current stream in bytes.

Remarks

A writable cursor buffers its payload in memory and supports at most MaxValue bytes; author larger payloads through a deferred stream source (AddStream(name, openRead, length) or AddStreamFromFile).

Exceptions

IOException

An I/O error occurs.

NotSupportedException

The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output.

ObjectDisposedException

Methods were called after the stream was closed.

NotSupportedException

Thrown when the cursor is read-only, or when value exceeds the MaxValue writable-cursor payload cap.

ObjectDisposedException

Thrown when the cursor has been disposed.

Write(byte[], int, int)

When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

public override void Write(byte[] buffer, int offset, int count)

Parameters

buffer byte[]

An array of bytes. This method copies count bytes from buffer to the current stream.

offset int

The zero-based byte offset in buffer at which to begin copying bytes to the current stream.

count int

The number of bytes to be written to the current stream.

Exceptions

ArgumentException

The sum of offset and count is greater than the buffer length.

ArgumentNullException

buffer is null.

ArgumentOutOfRangeException

offset or count is negative.

IOException

An I/O error occurred, such as the specified file cannot be found.

NotSupportedException

The stream does not support writing.

ObjectDisposedException

Write(byte[], int, int) was called after the stream was closed.

Write(ReadOnlySpan<byte>)

When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

public override void Write(ReadOnlySpan<byte> buffer)

Parameters

buffer ReadOnlySpan<byte>

A region of memory. This method copies the contents of this region to the current stream.

Remarks

A writable cursor buffers its payload in memory and supports at most MaxValue bytes; author larger payloads through a deferred stream source (AddStream(name, openRead, length) or AddStreamFromFile).

Exceptions

NotSupportedException

Thrown when the cursor is read-only, or when the write would grow the payload beyond the MaxValue writable-cursor cap.

ObjectDisposedException

Thrown when the cursor has been disposed.

WriteAsync(byte[], int, int, CancellationToken)

Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)

Parameters

buffer byte[]

The buffer to write data from.

offset int

The zero-based byte offset in buffer from which to begin copying bytes to the stream.

count int

The maximum number of bytes to write.

cancellationToken CancellationToken

The token to monitor for cancellation requests. The default value is None.

Returns

Task

A task that represents the asynchronous write operation.

Exceptions

ArgumentNullException

buffer is null.

ArgumentOutOfRangeException

offset or count is negative.

ArgumentException

The sum of offset and count is larger than the buffer length.

NotSupportedException

The stream does not support writing.

ObjectDisposedException

The stream has been disposed.

InvalidOperationException

The stream is currently in use by a previous write operation.

OperationCanceledException

The cancellation token was canceled. This exception is stored into the returned task.

NotSupportedException

Thrown when the cursor is read-only.

WriteAsync(ReadOnlyMemory<byte>, CancellationToken)

Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)

Parameters

buffer ReadOnlyMemory<byte>

The region of memory to write data from.

cancellationToken CancellationToken

The token to monitor for cancellation requests. The default value is None.

Returns

ValueTask

A task that represents the asynchronous write operation.

Exceptions

OperationCanceledException

The cancellation token was canceled. This exception is stored into the returned task.

NotSupportedException

Thrown when the cursor is read-only.

Applies to

ProductVersions
.NET8, 10