我把url
浏览器的地址栏和它下载 zip 文件到高清。压缩文件的大小在其属性中是 386 字节。
当我使用UnZipFiles
方法来提取文件时 - 它可以工作。但是,我想以编程方式下载并将其提取到内存中。我使用GetResultFromServer
方法来获取压缩内容。如标题所示,内容的大小与保存在 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
我的问题是如何提取返回的内容GetResultFromServer
?我尝试了以下方法:
var ms = new MemoryStream(Encoding.Unicode.GetBytes(res))
var s = new ZipInputStream(ms);
但我明白了Unable to read from this stream
。
更新
我试过var zipStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), CompressionMode.Decompress)
但我得到The magic number in GZip header is not correct
错误
代码
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();
}