Represents a stream that delegates its operations to another stream. This class is abstract and serves as a base class for stream decorators that modify or augment the behavior of an underlying stream without directly implementing all stream operations themselves.
public abstract class DelegatingStream : Stream
Public MustInherit Class DelegatingStream
Inherits Stream
public ref class DelegatingStream abstract : public Stream
DelegatingStream
.
The DelegatingStream
class is designed to be the base class for custom stream implementations that wrap another stream. Developers can inherit from DelegatingStream
and override specific methods (like Read
, Write
, Flush
, etc.) to add custom behavior, such as encryption, compression, logging, or data transformation. The GetStream
abstract method must be implemented to provide the underlying stream.
This pattern promotes code reuse and simplifies the creation of complex stream decorators by only requiring implementation of the modified operations, while other operations are automatically delegated to the base class's implementation (which in turn delegates to the underlying stream).
A common use case is creating a stream that logs all data read from or written to an underlying stream.
using System;
using System.IO;
public class LoggingDelegatingStream : DelegatingStream
{
private readonly Stream _innerStream;
private readonly TextWriter _logWriter;
public LoggingDelegatingStream(Stream innerStream, TextWriter logWriter)
{
_innerStream = innerStream ?? throw new ArgumentNullException(nameof(innerStream));
_logWriter = logWriter ?? throw new ArgumentNullException(nameof(logWriter));
}
protected override Stream GetStream()
{
return _innerStream;
}
public override int Read(byte[] buffer, int offset, int count)
{
int bytesRead = base.Read(buffer, offset, count);
if (bytesRead > 0)
{
_logWriter.WriteLine($"Read {bytesRead} bytes.");
// Optionally log the data itself, e.g., as hex or string
}
return bytesRead;
}
public override void Write(byte[] buffer, int offset, int count)
{
base.Write(buffer, offset, count);
_logWriter.WriteLine($"Wrote {count} bytes.");
// Optionally log the data itself
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Do NOT dispose of _innerStream here, as it might be managed elsewhere.
_logWriter?.Dispose(); // Dispose of log writer if it's managed here
}
base.Dispose(disposing);
}
}