Zip file from URL not valid

倖福魔咒の 提交于 2019-12-12 01:39:08

问题


I followed another post to be able to zip the content of an URL..

When I click my button Download, I "zip" the content of the URL and I save it in the default download folder...

So far this is my code:

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

it´s similar to this one (which zips the content of a folder... ) (It works correctly)

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

So, I want to do exactly the same with an URL..

THanks!


回答1:


at the end I use this code and It works like I wanted...

Thanks to all again!

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



回答2:


The example you provide will create an entry inside your zip file with the contents from the stream but you are doing nothing to save and return the actual zip file. You need to use the creation code from your second example.

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

this will return a zip file with one file in it called content.html containing the contents of the url stream



来源:https://stackoverflow.com/questions/24380134/zip-file-from-url-not-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!