【问题标题】:Read GZip compressed Data in Stream读取流中的 GZip 压缩数据
【发布时间】:2012-01-31 18:03:14
【问题描述】:

我的目标是使用 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 字节。正如 deguber 向我展示的那样,“字节”数组的长度约为 2k。所以看起来压缩后的字节数组的大小是对的,但是里面所有的值都是0。

可以。帮帮我?

【问题讨论】:

    标签: c# gzip


    【解决方案1】:

    您的Read 调用正试图从MemoryStreamend 读取 - 您还没有“倒回”它。您可以使用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,因为您随后将数据写入文件...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      相关资源
      最近更新 更多