我正在尝试压缩大量数据,有时在 100GB 左右,当我运行我编写的例程时,它看起来文件大小与以前的大小完全相同。还有其他人遇到过 GZipStream 的这个问题吗?
我的代码如下:
byte[] buffer = BitConverter.GetBytes(StreamSize);
FileStream LocalUnCompressedFS = File.OpenWrite(ldiFileName);
LocalUnCompressedFS.Write(buffer, 0, buffer.Length);
GZipStream LocalFS = new GZipStream(LocalUnCompressedFS, CompressionMode.Compress);
buffer = new byte[WriteBlock];
UInt64 WrittenBytes = 0;
while (WrittenBytes + WriteBlock < StreamSize)
{
fromStream.Read(buffer, 0, (int)WriteBlock);
LocalFS.Write(buffer, 0, (int)WriteBlock);
WrittenBytes += WriteBlock;
OnLDIFileProgress(WrittenBytes, StreamSize);
if (Cancel)
break;
}
if (!Cancel)
{
double bytesleft = StreamSize - WrittenBytes;
fromStream.Read(buffer, 0, (int)bytesleft);
LocalFS.Write(buffer, 0, (int)bytesleft);
WrittenBytes += (uint)bytesleft;
OnLDIFileProgress(WrittenBytes, StreamSize);
}
LocalFS.Close();
fromStream.Close();
StreamSize 是一个 8 字节的 UInt64 值,用于保存文件的大小。我将这 8 个字节原始写入文件的开头,所以我知道原始文件的大小。 Writeblock 的值为 32kb(32768 字节)。 fromStream 是从 FileStream 中获取数据的流。压缩数据前面的 8 个字节是否会导致问题?
最佳答案
我使用以下压缩代码运行了一个测试,它在 7GB 和 12GB 的文件上运行没有问题(这两个文件事先都知道可以“很好地”压缩)。这个版本适合你吗?
const string toCompress = @"input.file";
var buffer = new byte[1024*1024*64];
using(var compressing = new GZipStream(File.OpenWrite(@"output.gz"), CompressionMode.Compress))
using(var file = File.OpenRead(toCompress))
{
var bytesRead = 0;
while(bytesRead < buffer.Length)
{
bytesRead = file.Read(buffer, 0, buffer.Length);
compressing.Write(buffer, 0, buffer.Length);
}
}
你检查过documentation了吗? ?罢工>
The GZipStream class cannot decompress data that results in over 8 GB of uncompressed data.
您可能需要找到一个不同的库来支持您的需求或尝试将您的数据分解为 <=8GB
可以安全地“缝合”在一起的 block 。
关于c# - 大数据上的 GZipStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10621788/