Zip file from URL not valid

2019-09-05 08:26发布

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!

2条回答
走好不送
2楼-- · 2019-09-05 08:31

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

查看更多
Animai°情兽
3楼-- · 2019-09-05 08:42

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);
查看更多
登录 后发表回答