Reputation: 53
I'm creating a Zip file from files I'm downloading from the internet in bytes[], but I have an Issue, I don't know what I'm doing wrong... I generate the zip file but it's corrupted, the file size is correct(is not 0). Could you help me please? Maybe I didn't understand it well.
public <ActionResult> SomeFunction()
{
var invoices = GetInvoices();
WebClient client = new WebClient();
byte[] zipBytes = null;
using (var compressedFileStream = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, leaveOpen: true))
{
foreach (var invoice in invoices)
{
// This has correct values.
byte[] fileBytes = client.DownloadData(invoice.XmlUri);
// Create the instance of the file.
var zipEntry = zipArchive.CreateEntry(invoice.XmlFileName);
// Get the stream of the file.
using (var entryStream = new MemoryStream(fileBytes))
// Get the Stream of the zipEntry
using (var zipEntryStream = zipEntry.Open())
{
// Adding the file to the zip file.
entryStream.CopyTo(zipEntryStream);
}
}
}
zipBytes = compressedFileStream.ToArray();
}
return File(zipBytes , System.Net.Mime.MediaTypeNames.Application.Octet, "test.zip");
}
Upvotes: 1
Views: 5332
Reputation: 246998
Move
zipBytes = compressedFileStream.ToArray();
To after the archive has been disposed so that all data is flushed to the underlying stream.
public <ActionResult> SomeFunction() {
var invoices = GetInvoices();
WebClient client = new WebClient();
byte[] zipBytes = null;
using (var compressedFileStream = new MemoryStream()) {
using (ZipArchive zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Create, leaveOpen: true)) {
foreach (var invoice in invoices) {
// This has correct values.
byte[] fileBytes = client.DownloadData(invoice.XmlUri);
// Create the instance of the file.
var zipEntry = zipArchive.CreateEntry(invoice.XmlFileName);
// Get the stream of the file.
using (var entryStream = new MemoryStream(fileBytes))
// Get the Stream of the zipEntry
using (var zipEntryStream = zipEntry.Open()) {
// Adding the file to the zip file.
entryStream.CopyTo(zipEntryStream);
}
}
}
zipBytes = compressedFileStream.ToArray();
}
return File(zipBytes , System.Net.Mime.MediaTypeNames.Application.Octet, "test.zip");
}
Reference ZipArchive.Dispose()
This method finishes writing the archive and releases all resources used by the ZipArchive object. Unless you construct the object by using the
ZipArchive(Stream, ZipArchiveMode, Boolean)
constructor overload and set itsleaveOpen
parameter totrue
, all underlying streams are closed and no longer available for subsequent write operations.When you are finished using this instance of
ZipArchive
, callDispose()
to release all resources used by this instance. You should eliminate further references to thisZipArchive
instance so that the garbage collector can reclaim the memory of the instance instead of keeping it alive for finalization.
Upvotes: 1