DotNetZip从web服务下载zip文件

本文关键字:zip 文件 下载 服务 web DotNetZip | 更新日期: 2023-09-27 18:17:44

我正在尝试c#从web服务下载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);
        }
      }
    }
}

DotNetZip从web服务下载zip文件

显然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
}