Search code examples
c#zip

zip is invalid after HttpContext.Current.Response.BinaryWrite in c#


I want to create a zip file and then Download it

var zipfilep = CreateZipFile(fileByteArrays, sfileNames);

if (File.Exists(zipfilep))
{
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ContentType = "application/zip";
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(zipfilep));

    byte[] fileBytes = File.ReadAllBytes(zipfilep);
    HttpContext.Current.Response.BinaryWrite(fileBytes);

    HttpContext.Current.Response.Flush();
    File.Delete(zipfilep);
}
public string CreateZipFile(List<byte[]> files, List<string> sfileNames)
{
    string tempFolder = Server.MapPath("~/Upload");

    string zipFilePath = Path.Combine(tempFolder, GetGlobalResourceObject("GestioneContabilita", "RDLCViewer_ZipReportName").ToString() + ".zip");

    using (Package zip = Package.Open(zipFilePath, FileMode.Create))
    {
        for (int i = 0; i < files.Count; i++)
        {
            string zipPartUri = $"/{Uri.UnescapeDataString(sfileNames[i])}";
            Uri partUri = PackUriHelper.CreatePartUri(new Uri(zipPartUri, UriKind.Relative));

            PackagePart part = zip.CreatePart(partUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Normal);
            using (Stream partStream = part.GetStream())
            {
                partStream.Write(files[i], 0, files[i].Length);
            }
        }
    }
    return zipFilePath;
}

The file is created in Server.MapPath("~/Upload"), and it would be opened correctly. but when it is downloaded , the zip file could not be opened and it says

Windows cannot open the folder. C:\Users\UserProfile\Downloads\Reports.zip is invalid

and also I checked the Reports in Server.MapPath("~/Upload") has the size 15,175 KB but after HttpContext.Current.Response.BinaryWrite(fileBytes); in the C:\Users\UserProfile\Downloads\Reports.zip it turns to 15,569 KB

What could be the problem? I have to use .Net Framework 4.0


Solution

  • I added these line when I am copying the zip, and it fixed

    HttpContext.Current.Response.AddHeader("Content-Length", new FileInfo(zipfilep).Length.ToString());
    
    using (FileStream fs = new FileStream(zipfilep, FileMode.Open, FileAccess.Read))
    {
        fs.CopyTo(HttpContext.Current.Response.OutputStream);
    }