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

时间:2017-02-03 16:20:29

标签: c# azure stream compression gzipstream

我正在向System.IO.StreamWriter撰写文字。

基础流(在new StreamWriter(underlyingStream)中指定)写入远程文件。 (我不认为它的类型是相关的,但为了完整性,我会提到它是一个微软的天蓝色CloudBlobStream underlyingStream)。

现在,我想通过编写具有相同内容的其他压缩文件来扩展这一点,但在GZipOutputStream compressedUnderlyingStream和第二个StreamWriter之间使用CloudBlobStream

我一直在寻找一种方法来指定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);

1 个答案:

答案 0 :(得分:2)

我无法想到一个问题,但写下自己的文章是微不足道的:

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);
    }

    ...
}