How to extract zipped file received from HttpWebRe

2019-02-14 20:58发布

问题:

I put url to browser's address bar and it downloads the zip file to HD. The size of zipped file is 386 bytes as written in its properties.

When I use UnZipFiles method to extract the file - it works. But, I want to download programaticaly and extract it in memory. I use GetResultFromServer method to get zipped content. As shown in headers the size of the content is the same as the size of zipped file saved on HD:

content-disposition: attachment; filename=emaillog-xml.zip
Content-Length: 386
Cache-Control: private
Content-Type: application/zip
Date: Mon, 10 Sep 2012 08:28:28 GMT
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET

My question is how to extract the content returned by GetResultFromServer? I tried the following:

var ms = new MemoryStream(Encoding.Unicode.GetBytes(res))
var s = new ZipInputStream(ms);

but I get Unable to read from this stream.

UPDATED

I tried var zipStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), CompressionMode.Decompress) but I get The magic number in GZip header is not correct error

Code

private string GetResultFromServer(ElasticLogParams elasticLogParams)
{        
    var webRequest = (HttpWebRequest)WebRequest.Create(url);            
    var response = webRequest.GetResponse();

    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        var res = reader.ReadToEnd();
        var headers = response.Headers.ToString();              

        return res;
    }
}

public static void UnZipFiles(string zippedFilePath, Stream stream = null)
{
    var s = new ZipInputStream(stream ?? File.OpenRead(zippedFilePath));

    ZipEntry theEntry;
    while ((theEntry = s.GetNextEntry()) != null)
    {
        using (var streamWriter = File.Create(@"D:\extractedXML.xml"))
        {
            var size = 2048;
            var data = new byte[size];
            while (true)
            {
                size = s.Read(data, 0, size);
                if (size > 0)
                {
                    streamWriter.Write(data, 0, size);
                }
                else
                {
                    break;
                }
            }
            streamWriter.Close();
        }
    }
    s.Close();
}

回答1:

Give this a shot:

var response = webRequest.GetResponse() as HttpWebResponse;
var stream = response.GetResponseStream();
var s = new ZipInputStream(stream);

I believe you're very close and that you're using the right approach -- you can use this article to back that up -- their code is very similar.



回答2:

I'm using http://dotnetzip.codeplex.com/ I've not used it to download stuff, but to extract stuff that people upload to my server. I assume it should work perfectly the other way round too.

I've tried the built-in zip from microsoft too, but also had issues. So I gave it up and switched.