简体   繁体   中英

ZipArchive returning empty files c#

So I have achieved zipping the files but now I am having this another issues that the zip folder contains empty file. The size of the file zipped is 0 bytes.

This is how I am zipping my file

try
{
    var outPutDirectory = AppDomain.CurrentDomain.BaseDirectory;
    string logoimage = Path.Combine(outPutDirectory, "images\\error.png");

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.BufferOutput = false;
    HttpContext.Current.Response.ContentType = "application/zip";
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=pauls_chapel_audio.zip");

    using (MemoryStream ms = new MemoryStream())
    {
        // create new ZIP archive within prepared MemoryStream
        using (ZipArchive zip = new ZipArchive(ms, ZipArchiveMode.Create, true))
        {
            var demoFile = zip.CreateEntry(logoimage);
            // add some files to ZIP archive
        }
        ms.WriteTo(HttpContext.Current.Response.OutputStream);
    }

    return true;
}

Another issue is that the zipped folder has the same path as that of the image. So it is like

ZippFolder/A/B/C/image...

I just need

ZipFolder/content
var demoFile = zip.CreateEntry(logoimage);

This creates an entry in the ZIP file that has the name logoimage (ie /A/B/C/images/error.png or whatever is the full path).

But you never write to that entry, so it's empty. Also if you want to have a different path, you should specify it there:

var demoFile = zip.CreateEntry("content\\error.png");
using (StreamWriter writer = new StreamWriter(demoFile.Open()))
using (StreamReader reader = new StreamReader(logoimage))
{
    writer.Write(reader.ReadToEnd());
}

Alternatively, you could also skip the StreamWriter completely, and just write to the stream directly:

using (Stream stream = demoFile.Open())
using (StreamReader reader = new StreamReader(logoimage))
{
    reader.BaseStream.CopyTo(stream);
}

Btw. you can skip the outer MemoryStream in which you want to write your zip file first and then write that stream to the OutputStream . Instead, you can just write to that stream directly. Just pass it to the ZipFile constructor:

Stream output = HttpContext.Current.Response.OutputStream;
using (ZipArchive zip = new ZipArchive(output, ZipArchiveMode.Create, true))
{
    …
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM