如何将其转换为读取zip文件

本文关键字:读取 zip 文件 转换 | 更新日期: 2023-09-27 17:57:46

我正在从磁盘上读取一个解压缩的二进制文件,如下所示:

string fn = @"c:''MyBinaryFile.DAT";
byte[] ba = File.ReadAllBytes(fn);
MemoryStream msReader = new MemoryStream(ba);

我现在想通过使用压缩的二进制文件来提高I/O的速度。但是,我该如何将其放入上述模式中呢?

string fn = @"c:''MyZippedBinaryFile.GZ";
//Put something here
byte[] ba = File.ReadAllBytes(fn);
//Or here
MemoryStream msReader = new MemoryStream(ba);

实现这一目标的最佳方式是什么。

我需要得到一个MemoryStream,因为我的下一步是反序列化它

您必须对文件的内容使用GZipStream

所以基本上应该是这样的:

string fn = @"c:''MyZippedBinaryFile.GZ";
byte[] ba = File.ReadAllBytes(fn);
using (MemoryStream msReader = new MemoryStream(ba))
using (GZipStream zipStream = new GZipStream(msReader, CompressionMode.Decompress))
{
    // Read from zipStream instead of msReader
}

为了解释flindenberg的有效注释,您也可以直接打开文件,而无需首先将整个文件读入内存:

string fn = @"c:''MyZippedBinaryFile.GZ";
using (FileStream stream = File.OpenRead(fn))
using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
{
    // Read from zipStream instead of stream
}

你需要以一个内存流结束吗?没有问题:

string fn = @"c:''MyZippedBinaryFile.GZ";
using (FileStream stream = File.OpenRead(fn))
using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
using (MemoryStream ms = new MemoryStream()
{
    zipStream.CopyTo(ms);
    ms.Seek(0, SeekOrigin.Begin); // don't forget to rewind the stream!
    // Read from ms
}

如何将其转换为读取zip文件