2012-01-31 131 views
1

我的目标是使用gzip压缩文件,然后将压缩字节写入Xml部分,这意味着我需要我的代码中的压缩字节数组。我发现GZip的所有例子都只是将字节直接写入文件。阅读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字节。当消除器显示我时,“字节”数组的长度为〜2k。所以它看起来像压缩字节数组的大小是正确的,但它的所有值是0.

可以s.o.帮我?

回答

4

你的Read通话正试图从末尾读取MemoryStream - 你还没有“倒带”它。你可能做到这一点与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这里,因为你再将数据写入到一个文件目前尚不清楚...