Class StreamDecoratorExtensions
Extension methods for the Stream class hidden behind the IDecorator<T> interface.
public static class StreamDecoratorExtensions
- Inheritance
-
StreamDecoratorExtensions
Examples
StreamDecoratorExtensions provides extension methods on Decorator.Enclose for stream operations including byte array conversion, string encoding, compression (GZip, Deflate, Brotli), and copying. This example creates multiple MemoryStream instances with sample text and demonstrates ToByteArray and ToByteArrayAsync, ToEncodedString and ToEncodedStringAsync, CopyStream and CopyStreamAsync, CompressGZip/DecompressGZip, CompressDeflate/DecompressDeflate, CompressBrotli/DecompressBrotli, and WriteAllAsync — all via the decorator pattern. Console output confirms each operation's result, such as byte array lengths, decompressed strings matching the original content, and stream copy sizes.
using System;
using Cuemon;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Cuemon;
using Cuemon.IO;
namespace MyApp.IO;
public class StreamDecoratorExtensionsExample
{
public async Task DemonstrateAsync()
{
// ---- InvokeToByteArray: convert stream to byte array ----
var source0 = new MemoryStream(Encoding.UTF8.GetBytes("Invoke test."));
Decorator.Enclose(source0).InvokeToByteArray();
// ---- ToByteArray: convert stream to byte array ----
var source1 = new MemoryStream(Encoding.UTF8.GetBytes("Hello, World!"));
byte[] bytes = Decorator.Enclose(source1).ToByteArray();
Console.WriteLine($"Byte array length: {bytes.Length}"); // 13
// ---- ToByteArrayAsync: async version ----
var source2 = new MemoryStream(Encoding.UTF8.GetBytes("Async bytes."));
byte[] asyncBytes = await Decorator.Enclose(source2).ToByteArrayAsync();
Console.WriteLine($"Async bytes length: {asyncBytes.Length}"); // 11
// ---- ToEncodedString: stream to string ----
var source3 = new MemoryStream(Encoding.UTF8.GetBytes("Read me as text."));
string text = Decorator.Enclose(source3).ToEncodedString(setup =>
{
setup.LeaveOpen = true;
});
Console.WriteLine(text); // Read me as text.
// ---- ToEncodedStringAsync: async stream to string ----
source3.Position = 0;
string textAsync = await Decorator.Enclose(source3).ToEncodedStringAsync(setup =>
{
setup.LeaveOpen = true;
});
Console.WriteLine(textAsync); // Read me as text.
// ---- CopyStreamAsync: async copy to destination stream ----
var source4 = new MemoryStream(Encoding.UTF8.GetBytes("Copy me."));
using var destination = new MemoryStream();
await Decorator.Enclose(source4).CopyStreamAsync(destination, bufferSize: 8192, changePosition: true);
Console.WriteLine($"Destination length: {destination.Length}"); // 8
// ---- CopyStream: synchronous copy ----
var source4b = new MemoryStream(Encoding.UTF8.GetBytes("Sync copy."));
using var dest4b = new MemoryStream();
Decorator.Enclose(source4b).CopyStream(dest4b);
Console.WriteLine($"Sync copy length: {dest4b.Length}"); // 9
// ---- CompressGZip / DecompressGZip ----
var source5 = new MemoryStream(Encoding.UTF8.GetBytes("GZip compress this."));
using var gzipCompressed = Decorator.Enclose(source5).CompressGZip();
Console.WriteLine($"GZip compressed size: {gzipCompressed.Length}");
gzipCompressed.Position = 0;
var gzipDecompressed = Decorator.Enclose(gzipCompressed).DecompressGZip();
var gzipText = await Decorator.Enclose(gzipDecompressed).ToEncodedStringAsync();
Console.WriteLine(gzipText); // GZip compress this.
// ---- CompressGZipAsync / DecompressGZipAsync ----
var source5b = new MemoryStream(Encoding.UTF8.GetBytes("Async GZip test."));
var gzipCompressedAsync = await Decorator.Enclose(source5b).CompressGZipAsync();
var gzipDecompressedAsync = await Decorator.Enclose(gzipCompressedAsync).DecompressGZipAsync();
var gzipAsyncText = await Decorator.Enclose(gzipDecompressedAsync).ToEncodedStringAsync();
Console.WriteLine(gzipAsyncText); // Async GZip test.
// ---- CompressDeflate / DecompressDeflate (sync) ----
var source6 = new MemoryStream(Encoding.UTF8.GetBytes("Deflate test."));
using var deflated = Decorator.Enclose(source6).CompressDeflate();
deflated.Position = 0;
var deflatedResult = Decorator.Enclose(deflated).DecompressDeflate();
var deflateText = await Decorator.Enclose(deflatedResult).ToEncodedStringAsync();
Console.WriteLine(deflateText); // Deflate test.
// ---- CompressDeflateAsync / DecompressDeflateAsync ----
var source6b = new MemoryStream(Encoding.UTF8.GetBytes("Async Deflate."));
var deflatedAsync = await Decorator.Enclose(source6b).CompressDeflateAsync();
var deflatedDecompAsync = await Decorator.Enclose(deflatedAsync).DecompressDeflateAsync();
var deflateAsyncText = await Decorator.Enclose(deflatedDecompAsync).ToEncodedStringAsync();
Console.WriteLine(deflateAsyncText); // Async Deflate.
// ---- ToByteArrayAsync / ToEncodedStringAsync (async byte/string conversion) ----
var sourceBytes = new MemoryStream(Encoding.UTF8.GetBytes("Async byte conversion."));
var bytesAsync = await Decorator.Enclose(sourceBytes).ToByteArrayAsync();
Console.WriteLine(bytesAsync.Length); // 22
sourceBytes.Position = 0;
var strAsync = await Decorator.Enclose(sourceBytes).ToEncodedStringAsync();
Console.WriteLine(strAsync); // Async byte conversion.
// ---- CompressBrotli / DecompressBrotli (sync, netstandard2.1+ or net9.0+) ----
var source7 = new MemoryStream(Encoding.UTF8.GetBytes("Brotli test."));
var brotliCompressed = Decorator.Enclose(source7).CompressBrotli();
brotliCompressed.Position = 0;
var brotliDecompressed = Decorator.Enclose(brotliCompressed).DecompressBrotli();
var brotliText = await Decorator.Enclose(brotliDecompressed).ToEncodedStringAsync();
Console.WriteLine(brotliText); // Brotli test.
// ---- CompressBrotliAsync / DecompressBrotliAsync ----
var source7b = new MemoryStream(Encoding.UTF8.GetBytes("Async Brotli."));
var brotliCompressedAsync = await Decorator.Enclose(source7b).CompressBrotliAsync();
var brotliDecompressedAsync = await Decorator.Enclose(brotliCompressedAsync).DecompressBrotliAsync();
var brotliAsyncText = await Decorator.Enclose(brotliDecompressedAsync).ToEncodedStringAsync();
Console.WriteLine(brotliAsyncText); // Async Brotli.
// ---- WriteAllAsync: write bytes to stream ----
var target = new MemoryStream();
byte[] data = Encoding.UTF8.GetBytes("Write this.");
await Decorator.Enclose(target).WriteAllAsync(data);
Console.WriteLine($"Written bytes: {target.Length}"); // 10
}
}
Methods
CompressBrotli(IDecorator<Stream>, Action<StreamCompressionOptions>)
Compress the enclosed Stream of the specified decorator using the Brotli algorithm.
public static Stream CompressBrotli(this IDecorator<Stream> decorator, Action<StreamCompressionOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<StreamCompressionOptions>The StreamCompressionOptions which may be configured.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.
CompressBrotliAsync(IDecorator<Stream>, Action<AsyncStreamCompressionOptions>)
Compress the enclosed Stream of the specified decorator using the Brotli algorithm.
public static Task<Stream> CompressBrotliAsync(this IDecorator<Stream> decorator, Action<AsyncStreamCompressionOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<AsyncStreamCompressionOptions>The AsyncStreamCompressionOptions which may be configured.
Returns
- Task<Stream>
A task that represents the asynchronous operation. The task result contains a compressed version of the enclosed Stream of the specified
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.
CompressDeflate(IDecorator<Stream>, Action<StreamCompressionOptions>)
Compress the enclosed Stream of the specified decorator using the Deflate algorithm.
public static Stream CompressDeflate(this IDecorator<Stream> decorator, Action<StreamCompressionOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<StreamCompressionOptions>The StreamCompressionOptions which may be configured.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.
CompressDeflateAsync(IDecorator<Stream>, Action<AsyncStreamCompressionOptions>)
Compress the enclosed Stream of the specified decorator using the Deflate algorithm.
public static Task<Stream> CompressDeflateAsync(this IDecorator<Stream> decorator, Action<AsyncStreamCompressionOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<AsyncStreamCompressionOptions>The AsyncStreamCompressionOptions which may be configured.
Returns
- Task<Stream>
A task that represents the asynchronous operation. The task result contains a compressed version of the enclosed Stream of the specified
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.
CompressGZip(IDecorator<Stream>, Action<StreamCompressionOptions>)
Compress the enclosed Stream of the specified decorator using the GZip algorithm.
public static Stream CompressGZip(this IDecorator<Stream> decorator, Action<StreamCompressionOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<StreamCompressionOptions>The StreamCompressionOptions which may be configured.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.
CompressGZipAsync(IDecorator<Stream>, Action<AsyncStreamCompressionOptions>)
Compress the enclosed Stream of the specified decorator using the GZip algorithm.
public static Task<Stream> CompressGZipAsync(this IDecorator<Stream> decorator, Action<AsyncStreamCompressionOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<AsyncStreamCompressionOptions>The AsyncStreamCompressionOptions which may be configured.
Returns
- Task<Stream>
A task that represents the asynchronous operation. The task result contains a compressed version of the enclosed Stream of the specified
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.
CopyStream(IDecorator<Stream>, Stream, int, bool)
Copies the contents of the enclosed Stream to the specified destination.
public static void CopyStream(this IDecorator<Stream> decorator, Stream destination, int bufferSize = 81920, bool changePosition = true)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> that wraps the source stream.
destinationStreamThe destination stream to which the contents of the source stream are copied.
bufferSizeintThe size of the buffer, in bytes. The value must be greater than zero. The default is 81920.
changePositionbooltrue to temporarily reset the position of the enclosed stream to the beginning before copying; otherwise, false to preserve the current position.
Exceptions
- ArgumentNullException
decoratoris null.
CopyStreamAsync(IDecorator<Stream>, Stream, int, bool, CancellationToken)
Asynchronously reads the bytes from the enclosed Stream of the specified decorator and writes them to the destination.
public static Task CopyStreamAsync(this IDecorator<Stream> decorator, Stream destination, int bufferSize = 81920, bool changePosition = true, CancellationToken ct = default)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
destinationStreamThe Stream to which the contents of the current stream will be copied.
bufferSizeintThe size of the buffer. This value must be greater than zero. The default size is 81920.
changePositionboolif
true, the enclosed Stream of the specifieddecoratorwill temporarily have its position changed to 0; otherwise the position is left untouched.ctCancellationTokenThe token to monitor for cancellation requests. The default value is None.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.
DecompressBrotli(IDecorator<Stream>, Action<StreamCopyOptions>)
Decompress the enclosed Stream of the specified decorator using Brotli data format specification.
public static Stream DecompressBrotli(this IDecorator<Stream> decorator, Action<StreamCopyOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<StreamCopyOptions>The StreamCopyOptions which may be configured.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.- InvalidDataException
The enclosed Stream of
decoratorwas compressed using an unsupported compression method.
DecompressBrotliAsync(IDecorator<Stream>, Action<AsyncStreamCopyOptions>)
Decompress the enclosed Stream of the specified decorator using Brotli data format specification.
public static Task<Stream> DecompressBrotliAsync(this IDecorator<Stream> decorator, Action<AsyncStreamCopyOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<AsyncStreamCopyOptions>The AsyncStreamCopyOptions which may be configured.
Returns
- Task<Stream>
A task that represents the asynchronous operation. The task result contains a decompressed version of the enclosed Stream of the specified
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.- InvalidDataException
The enclosed Stream of
decoratorwas compressed using an unsupported compression method.
DecompressDeflate(IDecorator<Stream>, Action<StreamCopyOptions>)
Decompress the enclosed Stream of the specified decorator using Deflate data format specification.
public static Stream DecompressDeflate(this IDecorator<Stream> decorator, Action<StreamCopyOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<StreamCopyOptions>The StreamCopyOptions which may be configured.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.- InvalidDataException
The enclosed Stream of
decoratorwas compressed using an unsupported compression method.
DecompressDeflateAsync(IDecorator<Stream>, Action<AsyncStreamCopyOptions>)
Decompress the enclosed Stream of the specified decorator using Deflate data format specification.
public static Task<Stream> DecompressDeflateAsync(this IDecorator<Stream> decorator, Action<AsyncStreamCopyOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<AsyncStreamCopyOptions>The AsyncStreamCopyOptions which may be configured.
Returns
- Task<Stream>
A task that represents the asynchronous operation. The task result contains a decompressed version of the enclosed Stream of the specified
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.- InvalidDataException
The enclosed Stream of
decoratorwas compressed using an unsupported compression method.
DecompressGZip(IDecorator<Stream>, Action<StreamCopyOptions>)
Decompress the enclosed Stream of the specified decorator using GZip data format specification.
public static Stream DecompressGZip(this IDecorator<Stream> decorator, Action<StreamCopyOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<StreamCopyOptions>The StreamCopyOptions which may be configured.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.- InvalidDataException
The enclosed Stream of
decoratorwas compressed using an unsupported compression method.
DecompressGZipAsync(IDecorator<Stream>, Action<AsyncStreamCopyOptions>)
Decompress the enclosed Stream of the specified decorator using GZip data format specification.
public static Task<Stream> DecompressGZipAsync(this IDecorator<Stream> decorator, Action<AsyncStreamCopyOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<AsyncStreamCopyOptions>The AsyncStreamCopyOptions which may be configured.
Returns
- Task<Stream>
A task that represents the asynchronous operation. The task result contains a decompressed version of the enclosed Stream of the specified
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratordoes not support write operations such as compression.- InvalidDataException
The enclosed Stream of
decoratorwas compressed using an unsupported compression method.
InvokeToByteArray(IDecorator<Stream>, int, bool)
Converts the enclosed Stream to its byte array representation.
public static byte[] InvokeToByteArray(this IDecorator<Stream> decorator, int bufferSize = 81920, bool leaveOpen = false)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> that wraps the source stream.
bufferSizeintThe size of the buffer, in bytes. The value must be greater than zero. The default is 81920.
leaveOpenbool
Returns
Remarks
This API supports the product infrastructure and is not intended to be used directly from application code.
Exceptions
- ArgumentNullException
decoratoris null.- ArgumentException
The enclosed Stream does not support reading.
ToByteArray(IDecorator<Stream>, Action<StreamCopyOptions>)
Converts the enclosed Stream of the specified decorator to its equivalent byte[] representation.
public static byte[] ToByteArray(this IDecorator<Stream> decorator, Action<StreamCopyOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<StreamCopyOptions>The StreamCopyOptions which may be configured.
Returns
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratorcannot be read from.
ToByteArrayAsync(IDecorator<Stream>, Action<AsyncStreamCopyOptions>)
Converts the enclosed Stream of the specified decorator to its equivalent byte[] representation.
public static Task<byte[]> ToByteArrayAsync(this IDecorator<Stream> decorator, Action<AsyncStreamCopyOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<AsyncStreamCopyOptions>The AsyncStreamCopyOptions which may be configured.
Returns
- Task<byte[]>
A task that represents the asynchronous operation. The task result contains a byte[] that is equivalent to the enclosed Stream of the specified
decorator.
Exceptions
- ArgumentNullException
decoratorcannot be null.- ArgumentException
The enclosed Stream of
decoratorcannot be read from.
ToEncodedString(IDecorator<Stream>, Action<StreamReaderOptions>)
public static string ToEncodedString(this IDecorator<Stream> decorator, Action<StreamReaderOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<StreamReaderOptions>The StreamReaderOptions which may be configured.
Returns
Remarks
IEncodingOptions will be initialized with DefaultPreambleSequence and DefaultEncoding.
Exceptions
- ArgumentNullException
decoratorcannot be null.- InvalidEnumArgumentException
setupwas initialized with an invalid Preamble.
ToEncodedStringAsync(IDecorator<Stream>, Action<AsyncStreamReaderOptions>)
public static Task<string> ToEncodedStringAsync(this IDecorator<Stream> decorator, Action<AsyncStreamReaderOptions> setup = null)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
setupAction<AsyncStreamReaderOptions>The AsyncStreamReaderOptions which may be configured.
Returns
- Task<string>
A task that represents the asynchronous operation. The task result contains a string containing the result of the enclosed Stream of the specified
decorator.
Remarks
IEncodingOptions will be initialized with DefaultPreambleSequence and DefaultEncoding.
Exceptions
- ArgumentNullException
decoratorcannot be null.- InvalidEnumArgumentException
setupwas initialized with an invalid Preamble.
WriteAllAsync(IDecorator<Stream>, byte[], CancellationToken)
Asynchronously writes a sequence of bytes to the enclosed Stream of the decorator with the entire size of the buffer starting from position 0.
public static Task WriteAllAsync(this IDecorator<Stream> decorator, byte[] buffer, CancellationToken ct = default)
Parameters
decoratorIDecorator<Stream>The IDecorator<T> to extend.
bufferbyte[]The buffer to write data from.
ctCancellationTokenThe token to monitor for cancellation requests.
Returns
- Task
A task that represents the asynchronous write operation.
Exceptions
- ArgumentNullException
decoratoris null -or-bufferis null.- NotSupportedException
The enclosed Stream of
decoratordoes not support writing.- ObjectDisposedException
The enclosed Stream of
decoratorhas been disposed.- InvalidOperationException
The enclosed Stream of
decoratoris currently in use by a previous write operation.