DotNetZip从webservice下载zip文件

时间:2014-08-12 17:05:52

标签: c# web-services dotnetzip

我正在尝试使用c#从webservice下载zip文件并在内存中提取一个条目但是当我尝试读取流时,如何在dotnetzip的文档中得到异常“此流不支持在“ZipFile.Read(stream)”部分寻找操作。

有人可以告诉我,我做错了什么?提前致谢

urlAuthentication="https://someurl/?login=foo&token=faa"
var request = (HttpWebRequest)WebRequest.Create(urlAuthentication);

request.Proxy = WebRequest.DefaultWebProxy;
request.Credentials = System.Net.CredentialCache.DefaultCredentials; ;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;


using (var ms = new MemoryStream())
{

   using (var response = (HttpWebResponse)request.GetResponse())
   {


      using (var stream =response.GetResponseStream())
      {

        using (ZipFile zipout = ZipFile.Read(stream))
        {
            ZipEntry entry = zipout["file1.xml"];
            entry.Extract(ms);
        }

      }
    }

}

1 个答案:

答案 0 :(得分:1)

显然dotnetzip需要一个流来支持搜索操作,而HttpWebResponse的响应流不支持搜索。

您可以先将整个文件下载到内存中,然后再访问它来解决此问题:

using (var ms = new MemoryStream())
{
    using (MemoryStream seekable = new MemoryStream())
    {
        using (var stream = response.GetResponseStream())
        {
            int bytes;
            byte[] buffer = new byte[1024];
            while ((bytes = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                seekable.Write(buffer, 0, bytes);
            }
        }

        seekable.Position = 0;
        using (ZipFile zipout = ZipFile.Read(seekable))
        {
            ZipEntry entry = zipout["file1.xml"];
            entry.Extract(ms);
        }
    }

    // access ms
}