在.net 2.0中的两个流之间复制

5 c# copy stream winforms

我一直在使用以下代码来压缩.Net 4.0中的数据:

public static byte[] CompressData(byte[] data_toCompress)
{

    using (MemoryStream outFile = new MemoryStream())
    {
        using (MemoryStream inFile = new MemoryStream(data_toCompress))
        using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
        {
            inFile.CopyTo(Compress);

        }
        return outFile.ToArray();
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,在.Net 2.0中,Stream.CopyTo方法不可用.所以,我尝试替换:

public static byte[] CompressData(byte[] data_toCompress)
{

    using (MemoryStream outFile = new MemoryStream())
    {
        using (MemoryStream inFile = new MemoryStream(data_toCompress))
        using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
        {
            //inFile.CopyTo(Compress);
            Compress.Write(inFile.GetBuffer(), (int)inFile.Position, (int)(inFile.Length - inFile.Position));
        }
        return outFile.ToArray();
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,当使用上述尝试时压缩失败 - 我收到一条错误消息:

无法访问MemoryStream的内部缓冲区.

有人可以在这个问题上提供任何帮助吗?我真的不确定这里还有什么可做的.

谢谢,埃文

The*_*ing 7

这是直接用于.Net 4.0 Stream.CopyTo方法的代码(bufferSize是4096):

byte[] buffer = new byte[bufferSize];
int count;
while ((count = this.Read(buffer, 0, buffer.Length)) != 0)
    destination.Write(buffer, 0, count);
Run Code Online (Sandbox Code Playgroud)


Bro*_*ass 3

既然您已经可以访问该数组,为什么不这样做:

using (MemoryStream outFile = new MemoryStream())
{
    using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
    {
        Compress.Write(data_toCompress, 0, data_toCompress.Length);
    }
    return outFile.ToArray();
}
Run Code Online (Sandbox Code Playgroud)

在您使用的示例代码中很可能inFile.GetBuffer()会抛出异常,因为您没有使用正确的构造函数- 并非所有MemoryStream实例都允许您访问内部缓冲区 - 您必须在文档中查找:

根据字节数组的指定区域、按指定设置的 CanWrite 属性以及按指定设置调用 GetBuffer 的能力来初始化 MemoryStream 类的新实例。

这应该可行 - 但在建议的解决方案中无论如何都不需要:

using (MemoryStream inFile = new MemoryStream(data_toCompress, 
                                              0, 
                                              data_toCompress.Length, 
                                              false, 
                                              true))
Run Code Online (Sandbox Code Playgroud)