Search code examples
c#web-servicesdotnetzip

DotNetZip download zip file from a webservice


I'm trying on c# to download a zip file from a webservice and extract an entry in the memory but when I try to read the stream how is in the documentation of the dotnetzip I get the exception "This stream does not support seek operations” in the "ZipFile.Read(stream)" part.

Somebody could tell me what I'm doing wrong? Thanks in advance

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);
        }

      }
    }

}

Solution

  • Apparently dotnetzip requires a stream to support seek operations and the response stream of a HttpWebResponse does not support seeking.

    You can solve this issue by first downloading the entire file in memory, and then accessing it:

    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
    }