2013-10-03 47 views
1

我基本上是从msdn直接复制了这段代码示例,并做了一些最小的修改。 CopyTo方法默默无闻,我不知道为什么。什么会导致这种行为?它传递一个78 KB的压缩文件夹,其中包含一个文本文件。返回的FileInfo对象指向一个0 KB文件。没有例外被抛出。DeflateStream CopyTo不写任何东西,也不会抛出异常

public static FileInfo DecompressFile(FileInfo fi) 
    { 
     // Get the stream of the source file. 
     using (FileStream inFile = fi.OpenRead()) 
     { 
      // Get original file extension, 
      // for example "doc" from report.doc.cmp. 
      string curFile = fi.FullName; 
      string origName = curFile.Remove(curFile.Length 
        - fi.Extension.Length); 

      //Create the decompressed file. 
      using (FileStream outFile = File.Create(origName)) 
      { 
       // work around for incompatible compression formats found 
       // here http://george.chiramattel.com/blog/2007/09/deflatestream-block-length-does-not-match.html 
       inFile.ReadByte(); 
       inFile.ReadByte(); 

       using (DeflateStream Decompress = new DeflateStream(inFile, 
        CompressionMode.Decompress)) 
       { 
        // Copy the decompression stream 
        // into the output file. 
        Decompress.CopyTo(outFile); 

        return new FileInfo(origName); 
       } 
      } 
     } 
    } 
+0

什么类型的文件正在尝试读取和解压缩? .gz,.zip或其他内容? – huntharo

+0

@huntharo它是一个.zip。 – evanmcdonnal

回答

2

在评论中,你说你试图解压zip文件。 DeflateStream类不能在zip文件中使用。您提到的MSDN example使用DeflateStream来创建单独的压缩文件,然后解压缩它们。

虽然zip文件可能使用相同的算法(不确定),但它们不仅仅是单个文件的压缩版本。一个zip文件是一个容器,可以容纳很多文件和/或文件夹。

如果您可以使用.NET Framework 4.5,我会建议使用新的ZipFileZipArchive类。如果您必须使用较早的框架版本,则可以使用免费库(如DotNetZipSharpZipLib)。

+1

不幸的是我在.NET 4上。我最初尝试使用'Zipfile'类,但意识到它不是一个选项。我可能不得不与其中一个第三方库去,但不愿意。 – evanmcdonnal