如何使用一个 StreamWriter 写入多个底层流?

How to use one StreamWriter to write to multiple underlying streams?

我正在写文本到 System.IO.StreamWriter

底层流(在new StreamWriter(underlyingStream)中指定)写入远程文件。 (我不认为它的类型是相关的,但为了完整起见,我会提到它是微软 azure CloudBlobStream underlyingStream)。

现在,我想通过在 StreamWriter 和第二个 CloudBlobStream 之间使用 GZipOutputStream compressedUnderlyingStream 来扩展它,同时编写一个具有相同内容的额外压缩文件。

我正在寻找一种方法来将两个 CloudBlobStream 指定为 StreamWriter 的基础流。但我找不到办法。是否存在某种可以组合两个底层流的流类型?或者我怎样才能解决这个问题?请注意,我希望所有内容都保留为流,以最大程度地减少内存中的数据量。

//disregard lack of using statements for this example's sake
CloudBlobStream blobStream = blob.OpenWrite();
CloudBlobStream compressedBlobStream = compressedBlob.OpenWrite();
GZipOutputStream compressorStream = new GZipOutputStream(compressedBlobStream);
//I make the streamwriter here for the regular blob,
///but how could I make the same streamwriter also write to the compressedBlob at the same time?
TextWriter streamWriter = new StreamWriter(blobStream, Encoding.UTF8);

我一时想不出来,但自己写一个也很简单:

class MultiStream : Stream
{
    private List<Stream> streams;

    public Streams(IEnumerable<Stream> streams)
    {
        this.streams = new List<Stream>(streams);
    }

    ...

    public override void Write(byte[] buffer, int offset, int count)
    {
        foreach(Stream stream in streams)
            stream.Write(buffer, offset, count);
    }

    ...
}