gzipstream.copyto .net 3.5中的替代和简单方法

时间:2010-10-21 09:00:27

标签: c# .net .net-3.5

喜 在.net 4中的这段代码中,我使用了gzipstream的copyto方法

        System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
        GZipStream DecompressOut = new GZipStream(ms, System.IO.Compression.CompressionMode.Decompress);
        MemoryStream outmem = new MemoryStream();
        DecompressOut.copyto(outmem);
        FileStream outFile = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
        StreamWriter m_streamWriter = new StreamWriter(outFile);

我怎样才能直接将GZipStream写入MemoryStream或FileStream?

1 个答案:

答案 0 :(得分:5)

在流之间进行复制非常基本:

public static long CopyTo(this Stream source, Stream destination) {
    byte[] buffer = new byte[2048];
    int bytesRead;
    long totalBytes = 0;
    while((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) {
        destination.Write(buffer, 0, bytesRead);
        totalBytes += bytesRead;
    }
    return totalBytes;
}

所以只需将其插入即可,您应该进行排序:

using(var ms = new MemoryStream(byteArray))
using(var gzip = new GZipStream(ms, CompressionMode.Decompress))
using (var file = new FileStream(fileName, FileMode.OpenOrCreate,
                                           FileAccess.Write)) {
    gzip.CopyTo(file);
}