来自URL的Zip文件无效

时间:2014-06-24 06:52:10

标签: c# webclient dotnetzip

我关注了另一篇文章,以便能够压缩网址的内容..

当我点击我的按钮下载时,我“压缩”了URL的内容,并将其保存在默认的下载文件夹中......

到目前为止,这是我的代码:

WebClient wc = new WebClient(); 

ZipFile zipFile = new ZipFile();

string filename = "myfile.zip";

zipFile.Password = item.Password;

Stream s = wc.OpenRead(myUrl); 

zipFile.AddeEntry(filename, s);

return File(s, "application/zip", filename);

它类似于这个(它压缩了文件夹的内容......)(它可以正常工作)

ZipFile zipFile = new ZipFile();

zipFile.Password = item.Password;

zipFile.AddDirectory(sourcePath, "");

MemoryStream stream = new MemoryStream();
zipFile.Save(stream);
zipFile.Dispose();
stream.Seek(0, SeekOrigin.Begin);

return File(stream, "application/zip", fileName);

所以,我想用URL做同样的事情。

谢谢!

2 个答案:

答案 0 :(得分:2)

最后我使用了这段代码,它就像我想要的那样......

再次感谢所有人!

 string fileName = "filename" + ".zip";

 MemoryStream stream = new MemoryStream();

 ZipFile zipFile = new ZipFile();     

 WebRequest webRequest = WebRequest.Create(myUrl);

 webRequest.Timeout = 1000;

 WebResponse webResponse = webRequest.GetResponse();

 using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
 {
     string content = reader.ReadToEnd();
     zipFile.AddEntry("myfile.txt", content);
 }

 zipFile.Save(stream);
 zipFile.Dispose();
 stream.Seek(0, SeekOrigin.Begin);

 return File(stream, "application/zip", fileName);

答案 1 :(得分:0)

您提供的示例将在您的zip文件中创建一个条目,其中包含流中的内容,但您无法保存并返回实际的zip文件。您需要使用第二个示例中的创建代码。

// name of zip file
string filename = "myfile.zip";
// filename of content
string contentName = "mypage.html";
WebClient wc = new WebClient(); 
ZipFile zipFile = new ZipFile();

zipFile.Password = item.Password;
Stream s = wc.OpenRead(myUrl); 
zipFile.AddeEntry(contentName, s);
MemoryStream stream = new MemoryStream();
zipFile.Save(stream);
zipFile.Dispose(); // could use using instead
s.Dispose(); // could use using instead....
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/zip", fileName);

这将返回一个zip文件,其中包含一个名为content.html的文件,其中包含url stream的内容

相关问题