Downloading Zip files with webclient seems to not be working properly for me, once downloaded and saved the zip file comes up as invalid or corrupted, opening with a zip reader. However the source zip file seems to be fine, its a valid zip.
Download code:
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(URL), downloadZipFilename);
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
//unzip
using (ZipFile zipFile = ZipFile.Read(currentTemporaryDownloadFileUrl))
{
zipFile.ExtractAll(currentTargetFileUrl);
}
File.Delete(currentTemporaryDownloadFileUrl);
DownloadFinished(this,EventArgs.Empty);
Console.WriteLine("File finished downloading.");
}
The zip extract comes up as corrupt.
Server code:
//send file
e.Response.Connection.Type = HttpServer.Headers.ConnectionType.Close;
byte[] buffer = ReadFile(filePath);
e.Response.Body.Write(buffer, 0, buffer.Length);
Readfile on server:
public static byte[] ReadFile(string filePath)
{
// this method is limited to 2^32 byte files (4.2 GB)
FileStream fs = File.OpenRead(filePath);
try
{
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
fs.Close();
return bytes;
}
finally
{
fs.Close();
}
}
What’s wrong here?
Thanks,
Christian Stewart
Rather than, inefficiently, loading the ZIP file into memory, then writing it out, how about using
TransmitFile streams directly to the output stream without buffering, thus minimising memory consumption.