我正在尝试使用GzipStream类实现逐块压缩。NET Core 3.1,Visual Studio 2019,控制台应用程序。我的操作系统是Windows 10。我认为这应该是可能的,因为gzip文件按照格式规范由一个又一个独立的块组成。但我得到的结果文件已损坏。这是代码:
using System;
using System.Globalization;
using System.IO;
using System.IO.Compression;
namespace GzipToMemoryStreamExample
{
class Program
{
private static int blockSize;
private static string sourceFileName = "e:\SomeFolder\SomeFile.ext";
private static byte[] currentBlock;
private static FileStream readingStream;
private static FileStream writingStream;
static void Main(string[] args)
{
Console.WriteLine("Enter block size:");
string blockSizeStr = Console.ReadLine();
int.TryParse(blockSizeStr, out blockSize);
readingStream = new FileStream(sourceFileName, FileMode.Open);
string resultingFileName = Path.ChangeExtension(sourceFileName, ".gz");
CreateAndOpenResultingFile(resultingFileName);
while (ReadBlock())
{
byte[] processedBlock = ProcessBlock(currentBlock);
writingStream.Write(processedBlock, 0, processedBlock.Length);
}
readingStream.Dispose();
writingStream.Dispose();
Console.WriteLine("Finished.");
Console.ReadKey();
}
private static bool ReadBlock()
{
bool result;
int bytesRead;
currentBlock = new byte[blockSize];
bytesRead = readingStream.Read(currentBlock, 0, blockSize);
result = bytesRead > 0;
return result;
}
private static byte[] ProcessBlock(byte[] sourceData)
{
byte[] result;
using (var outputStream = new MemoryStream())
{
using var compressionStream = new GZipStream(outputStream, CompressionMode.Compress);
compressionStream.Write(sourceData, 0, sourceData.Length);
result = outputStream.ToArray();
}
return result;
}
private static void CreateAndOpenResultingFile(string fileName)
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
writingStream = File.Create(fileName);
}
}
}
当我查看结果文件时,我发现结果在某种程度上取决于我选择的块大小。如果它小于~100Kb;压缩的";每个块的大小为10字节,这导致了非常小的无用文件。如果块的大小大于~100 Kb,则文件的大小会变得相当大,约为原始文件的80%,但仍已损坏
我还检查了块标题,结果发现它们很奇怪。OS设置为TOPS-20(0x0a值(,块末尾的ISIZE总是完全错误的
我犯了什么错?
只需移动result=outputStream.ToArray((即可解决如Mark Adler在评论中所建议的那样,使用范围从压缩流中移出。
private static byte[] ProcessBlock(byte[] sourceData)
{
byte[] result;
using (var outputStream = new MemoryStream())
{
using (var compressionStream = new GZipStream(outputStream, CompressionMode.Compress))
{
compressionStream.Write(sourceData, 0, sourceData.Length);
}
result = outputStream.ToArray();
}
return result;
}