Skip to main content
 首页 » 编程设计

c#之读取 Stream 中的 GZip 压缩数据

2024年02月23日17jiqing9006

我的目标是使用 gzip 压缩文件,然后将压缩字节写入 Xml 部分,这意味着我的代码中需要压缩字节数组。我发现的所有 GZip 示例都只是将字节直接写入文件。

这是我的代码:

public ContainerFile(string[] inputFiles, string Output) 
    { 
        XmlDocument doc = new XmlDocument(); 
        XmlNode root; 
 
        FileInfo fi; 
        FileStream fstream; 
        BinaryReader reader; 
        GZipStream gstream; 
 
 
 
        root = doc.CreateElement("compressedFile"); 
        doc.AppendChild(root); 
 
        foreach (string f in inputFiles) 
        { 
            fstream = File.OpenRead(f); 
            MemoryStream s = new MemoryStream(); 
 
            byte[] buffer = new byte[fstream.Length]; 
            // Read the file to ensure it is readable. 
            int count = fstream.Read(buffer, 0, buffer.Length); 
            if (count != buffer.Length) 
            { 
                fstream.Close(); 
                //Console.WriteLine("Test Failed: Unable to read data fromfile"); 
            return; 
            } 
            fstream.Close(); 
 
            gstream = new GZipStream(s, CompressionMode.Compress, true); 
            gstream.Write(buffer, 0, buffer.Length); 
            gstream.Flush(); 
 
 
            byte[] bytes = new byte[s.Length]; 
 
            s.Read(bytes, 0, bytes.Length); 
 
            File.WriteAllBytes(@"c:\compressed.gz", bytes); 
 
        } 

出于调试原因,我只是尝试在数据加载后将其写入文件。

因此,输入文件的长度约为 4k 字节。正如 degubber 向我展示的那样,“字节”数组的长度约为 2k。所以看起来压缩字节数组的大小是正确的,但是里面的所有值都是0。

可以吗帮帮我?

请您参考如下方法:

您的 Read 调用正在尝试从 MemoryStream 的end 读取 - 您还没有“回绕”它。您可以使用 s.Position = 0; 来做到这一点 - 但只调用 MemoryStream.ToArray 会更简单。

请注意,我会亲自尝试不从流中读取,假设整个数据将一次性可用,就像您开始时所做的那样。您还应该对流使用 using 语句,以避免在抛出异常时泄漏句柄。但是,无论如何,使用 File.ReadAllBytes 会更简单:

byte[] inputData = File.ReadAllBytes(); 
using (var output = new MemoryStream()) 
{ 
    using (var compression = new GZipStream(output, CompressionMode.Compress, 
                                            true)) 
    { 
        compression.Write(inputData, 0, inputData.Length); 
    } 
    File.WriteAllBytes(@"c:\compressed.gz", output.ToArray()); 
} 

目前尚不清楚为什么首先要在这里使用 MemoryStream,因为您随后要将数据写入文件...