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

我一直在使用以下代码来压缩.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(); } } 

但是,在.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(); } } 

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

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

任何人都可以就此问题提供任何帮助吗? 我真的不确定这里还有什么可做的。

谢谢,埃文

由于您已经可以访问该arrays,为什么不这样做:

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

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

基于字节数组的指定区域初始化MemoryStream类的新实例,CanWrite属性设置为指定, 并且能够按指定调用GetBuffer

这应该有效 – 但在建议的解决方案中无论如何都不需要:

 using (MemoryStream inFile = new MemoryStream(data_toCompress, 0, data_toCompress.Length, false, true)) 

这是直接使用.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); 

为什么要使用数组构造内存流,然后尝试将数组拉出内存流?

你可以做Compress.Write(data_toCompress, 0, data_toCompress.Length);

如果需要替换CopyTo的function,可以创建一些长度的缓冲区数组,从源流中读取数据并将该数据写入目标流。

你可以试试

 infile.WriteTo(Compress); 

尝试更换线:

 Compress.Write(inFile.GetBuffer(), (int)inFile.Position, (int)(inFile.Length - inFile.Position)); 

有:

 Compress.Write(data_toCompress, 0, data_toCompress.Length); 

你可以完全摆脱这条线:

 using (MemoryStream inFile = new MemoryStream(data_toCompress)) 

编辑:在这里找一个例子: 为什么gzip / deflate压缩一个小文件导致许多尾随零?

您应该在这两个流之间手动读写:

  private static void CopyStream(Stream from, Stream to) { int bufSize = 1024, count; byte[] buffer = new byte[bufSize]; count = from.Read(buffer, 0, bufSize); while (count > 0) { to.Write(buffer, 0, count); count = from.Read(buffer, 0, bufSize); } } 

开源NuGet包Stream.CopyTo为所有版本的.NET Framework实现Stream.CopyTo

可在GitHub和NuGet上获得 ( Install-Package Stream.CopyTo