GZipStream做gzipping,但unzipping文件以“意外结束的数据”结束

本文关键字:结束 意外 数据 文件 gzipping unzipping GZipStream | 更新日期: 2023-09-27 18:02:05

有人知道为什么我得到"意外结束的数据"错误信息时,解压缩gzip文件?

为了验证字节数据没有损坏,我使用FooTest4.csv写入文件,并且能够成功打开文件。

两个'FooTest3.csv.gz and 'FooTest2.csv.gz在解压缩时遇到"Unexpected end of data"

    public static List<byte> CompressFile(List<byte> parmRawBytes)
    {
        //Initialize variables...
        List<byte> returnModifiedBytes = null;
        File.WriteAllBytes(@"X:'FooTest4.csv", parmRawBytes.ToArray());
        using (var memoryStream = new MemoryStream())
        {
            using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, false))
            {
                gzipStream.Write(parmRawBytes.ToArray(), 0, parmRawBytes.ToArray().Length);
                gzipStream.Flush();
                File.WriteAllBytes(@"X:'FooTest3.csv.gz", memoryStream.ToArray());
                returnModifiedBytes = memoryStream.ToArray().ToList();
            }
        }
        File.WriteAllBytes(@"X:'FooTest2.csv.gz", returnModifiedBytes.ToArray());
        return returnModifiedBytes;
    }

GZipStream做gzipping,但unzipping文件以“意外结束的数据”结束

GZipStream需要被关闭,以便它可以将一些终止数据写入缓冲区的末尾以完成gzip编码。

byte[] inputBytes = ...;
using (var compressedStream = new MemoryStream())
{
    using (var compressor = new GZipStream(compressedStream, CompressionMode.Compress))
    {
        compressor.Write(inputBytes, 0, inputBytes.Length);
    }
    // get bytes after the gzip stream is closed 
    File.WriteAllBytes(pathToFile, compressedStream.ToArray());
}

与其加载、压缩和保存字节,不如同时进行压缩和写入。我也不知道你为什么用List<Byte>而不是byte[],也许这可能是它。

void CompressFile(string inputPath, string outputPath)
{
   Stream readStream = new FileStream(inputPath, Filemode.Open);
   Stream writeStream = new FileStream(outputPath, FileMode.Create);
   Stream compressionStream = new GZipStream(writeStream. CompressionMode.Compress);
   byte[] data = new byte[readStream.Length];
   readStream.Read(data, 0, data.Length);
   compressionStream.Write(data, 0, data.Length);
   readStream.Close();
   writeStream.Close();    
}
byte[] CompressFile(string inputPath)
{
  byte[] data = File.ReadAllBytes(inputPath);
  MemoryStream memStream = new MemoryStream(data);
  var gzipStream = new GZipStream(memStream, CompressionMode.Compress);
  gzipStream.Write(data, 0, data.Length);
  gzipStream.Close();
  return gzipStream.ToArray();
}

PS:我在文本编辑器中编写代码,所以可能会有错误。你还说错误是在"解拉链"上,为什么不给我们看解邮编?