2011-06-16 53 views
4

我想下载并提取C#中的zip文件,特别是DotNetZip。提取内存中的zip文件与C#失败DotNetZip

当我运行这段代码...

 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(reportUrl); 
     HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); 
     Stream stream = response.GetResponseStream(); 
     MemoryStream ms = new MemoryStream(); 

     stream.CopyTo(ms); 
     ms.Seek(0, 0); 
     ZipInputStream zip = new ZipInputStream(ms); 
     zip.Seek(0, 0); 

     ZipEntry e = zip.GetNextEntry(); 
     string s = e.FileName; 

     MemoryStream ms2 = new MemoryStream(); 
     e.Extract(ms2); 

后的提取方法执行,我得到...

 $exception {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException} 

有什么想法?谢谢!

Here's what the object looks like before the method runs

+1

我的直接想法是InputStream为空 – Ell 2011-06-16 18:48:47

+0

你试过使用不同的memorystream实例吗? – 2011-06-16 18:49:39

+1

“解压缩方法执行后”是什么意思?抛出异常之前它是否正确执行? Extract后的下一行代码是什么? – 2011-06-16 18:51:46

回答

3

这很难说,为什么你的代码不能正常工作。我会通过简化它,并确保我妥善处理所有可支配的资源,如流开始:

class Program 
{ 
    static void Main() 
    { 
     var url = "http://downloads.sourceforge.net/project/junit/junit/3.8.1/junit3.8.1.zip"; 
     using (var client = new WebClient()) 
     using (var zip = ZipFile.Read(client.DownloadData(url))) 
     { 
      foreach (var entry in zip) 
      { 
       entry.Extract("."); 
      }   
     } 
    } 
} 

确保您签的文档,使用DotNetZip库many useful examples

+0

嘿,感谢Darin的回答!但是,这并不适合我(.NET 4.0,最新版本的DotNetZip)。我不想屠杀你的答案通过依赖我的不存在的C#使它工作...从Byte.Array(DownloadData返回值)到IO.Stream,Read命令所需的最佳方式是什么? – 2011-06-16 19:06:59

+0

@Charles Offenbacher ,你得到了什么错误?因为我刚刚在我的Win7 x64 VS2010 .NET 4.0上测试了这段代码,它的工作非常好。 – 2011-06-16 19:07:30

+0

ZipFile.Read似乎只接受一个文件名字符串或Stream for me ...怪异的我'在VS2010 .NET 4.0 Win7的x64太....嗯... 1秒 – 2011-06-16 19:08:43