使用DeflateStream时避免复制压缩数据

时间:2017-12-14 08:45:02

标签: c# deflatestream

假设我们已经给出了一个API函数f(Stream s)来将包含在流中的二进制数据放入数据库中。我想使用f将文件放入数据库,但我想提前压缩数据。因此,我认为我可以做到以下几点:

var fileStream= File.OpenRead(path);
using(var dstream = new DeflateStream(fileStream, CompressionLevel.Optimal))
   f(dstream);

但似乎DeflateStream只写入流fileStream但在压缩时不会从中读取。在我发现的所有示例中,流的CopyTo方法用于压缩或解压缩。但这意味着我必须在将压缩数据传递到f之前将其保留在内存中,例如:

var memoryStream = new MemoryStream();
using(var fileStream= File.OpenRead(path)) 
  using(var dstream = new DeflateStream(memoryStream, CompressionLevel.Optimal)) {
    fileStream.CopyTo(dstream);
    memoryStream.Seek(0, SeekOrigin.Begin);
    f(memoryStream);
  }    

有没有办法避免使用MemoryStream?

更新 为了一些评论员的持久性,我添加了一个完整的例子:

using System;
using System.IO;
using System.IO.Compression;

public class ThisWouldBeTheDatabaseClient {
  public void f(Stream s) {
    // some implementation I don't have access to
    // The only thing I know is that it reads data from the stream in some way.
    var buffer = new byte[10];
    s.Read(buffer,0,10);
  }
}

public class Program {
  public static void Main() {
    var dummyDatabaseClient = new ThisWouldBeTheDatabaseClient();
    var dataBuffer = new byte[1000];
    var fileStream= new MemoryStream( dataBuffer ); // would be "File.OpenRead(path)" in real case
    using(var dstream = new DeflateStream(fileStream, CompressionLevel.Optimal))
        dummyDatabaseClient.f(dstream);
  }
}

f的虚拟实现中的读取操作会引发异常: InvalidOperationException:不支持从压缩流中读取。结束评论中的讨论,我假设需要DeflateStream无法实现行为,但第三方库中也有其他选择。

2 个答案:

答案 0 :(得分:2)

DeflateStream只是一个包装器,需要一个压缩数据流。所以你必须使用两个流。

  

有没有办法避免使用MemoryStream?

是。

您需要一个流来存储临时数据,而不会占用(太多)内存。而是使用MemoryStream,您可以使用临时文件

对于懒惰的人(就像我在第一时间),让我们创建一个类似于MemoryStream

的课程
public class TempFileStream : FileStream
{
    public TempFileStream() : base(
        path: Path.GetTempFileName(),
        mode: FileMode.Open,
        access: FileAccess.ReadWrite,
        share: FileShare.None,
        bufferSize: 4096,
        options: FileOptions.DeleteOnClose | FileOptions.Asynchronous | FileOptions.Encrypted | FileOptions.RandomAccess)
    {
    }
}

这里的重要部分是FileOptions.DeleteOnClose,它将在您处理流时删除临时文件。

然后使用它

using (var compressedStream = new TempFileStream())
{
    using (var deflateStream = new DeflateStream(
        stream: compressedStream,
        compressionLevel: CompressionLevel.Optimal,
        leaveOpen: true))
    using (var fileStream = File.OpenRead(path))
    {
        fileStream.CopyTo(deflateStream);
    }

    f(compressedStream);
}

答案 1 :(得分:2)

您可以使用SharpCompress。它的DeflateStream允许您即时读取压缩数据,这正是您想要的。

以下是基于Rufo爵士的完整示例:

using System;
using System.IO;
using SharpCompress.Compressors;
using SharpCompress.Compressors.Deflate;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var dataBuffer = Enumerable.Range(1, 50000).Select(e => (byte)(e % 256)).ToArray();

        using (var dataStream = new MemoryStream(dataBuffer))
        {
            // Note: this refers to SharpCompress.Compressors.Deflate.DeflateStream                
            using (var deflateStream = new DeflateStream(dataStream, CompressionMode.Compress))
            {
                ConsumeStream(deflateStream);
            }
        }
    }

    public static void ConsumeStream(Stream stream)
    {
        // Let's just prove we can reinflate to the original data...
        byte[] data;
        using (var decompressed = new MemoryStream())
        {
            using (var decompressor = new DeflateStream(stream, CompressionMode.Decompress))
            {
                decompressor.CopyTo(decompressed);
            }
            data = decompressed.ToArray();
        }
        Console.WriteLine("Reinflated size: " + data.Length);
        int errors = 0;
        for (int i = 0; i < data.Length; i++)
        {
            if (data[i] != (i + 1) % 256)
            {
                errors++;
            }
        }
        Console.WriteLine("Total errors: " + errors);
    }
}

或使用您的示例代码:

using System;
using System.IO;
using SharpCompress.Compressors;
using SharpCompress.Compressors.Deflate;

public class ThisWouldBeTheDatabaseClient {
  public void f(Stream s) {
    // some implementation I don't have access to
    // The only thing I know is that it reads data from the stream in some way.
    var buffer = new byte[10];
    s.Read(buffer,0,10);
  }
}

public class Program {
  public static void Main() {
    var dummyDatabaseClient = new ThisWouldBeTheDatabaseClient();
    var dataBuffer = new byte[1000];
    var fileStream= new MemoryStream( dataBuffer ); // would be "File.OpenRead(path)" in real case
    using(var dstream = new DeflateStream(
        fileStream, CompressionMode.Compress, CompressionLevel.BestCompression))
        dummyDatabaseClient.f(dstream);
  }
}

现在不会抛出异常,并将提供压缩数据。