I am trying to create a ZipArchive in memory and append several entries with binary data from database. The problem is that after loop, zip sent to client is invalid/empty. Can you please check my code?
using (MemoryStream _memory_stream = new MemoryStream())
{
using (ZipArchive _archive = new ZipArchive(_memory_stream, ZipArchiveMode.Create, true))
{
foreach (byte[] binaryData in this.FileBinaries)
{
ZipArchiveEntry _entry = _archive.CreateEntry(str_filename, CompressionLevel.Optimal);
using (Stream _entryStream = _entry.Open())
{
using (StreamWriter _writer = new StreamWriter(_entryStream))
{
_writer.Write(binaryData);
}
_entryStream.Close();
}
}
}
Response.AppendHeader("content-disposition", "attachment; filename=certificates.zip");
Response.ContentType = "application/zip";
Response.Write(_memory_stream);
}
Related
What I'm looking for is zip/compress S3 files without having them first downloaded to EFS or on a file system and then upload the zip file back to S3. Is there a C# way to achieve the same? I found the following post, but not sure its C# equivalent
https://www.antstack.io/blog/create-zip-using-lambda-with-files-streamed-from-s3/
I've written following code to zip files from a MemoryStream
public static void CreateZip(string zipFileName, List<FileInfo> filesToZip)
{
//zipFileName is the final zip file name
LambdaLogger.Log($"Zipping in progress for: {zipFileName}");
using (MemoryStream zipMS = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(zipMS, ZipArchiveMode.Create, true))
{
//loop through files to add
foreach (var fileToZip in filesToZip)
{
//read the file bytes
byte[] fileToZipBytes = File.ReadAllBytes(fileToZip.FullName);
ZipArchiveEntry zipFileEntry = zipArchive.CreateEntry(fileToZip.Name);
//add the file contents
using (Stream zipEntryStream = zipFileEntry.Open())
using (BinaryWriter zipFileBinary = new BinaryWriter(zipEntryStream))
{
zipFileBinary.Write(fileToZipBytes);
}
}
}
using (FileStream finalZipFileStream = new FileStream(zipFileName, FileMode.Create))
{
zipMS.Seek(0, SeekOrigin.Begin);
zipMS.CopyTo(finalZipFileStream);
}
}
}
But problem is how to make it read file directly from S3 and upload the compressed file.
public static async Task CreateZipFile(List<List<KeyVersion>> keyVersions)
{
using MemoryStream zipMS = new MemoryStream();
using (ZipArchive zipArchive = new ZipArchive(zipMS, ZipArchiveMode.Create, true))
{
foreach (var key in keyVersions)
{
foreach (var fileToZip in key)
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = "dev-s3-zip-bucket",
Key = fileToZip.Key
};
using GetObjectResponse response = await s3client.GetObjectAsync(request);
using Stream responseStream = response.ResponseStream;
ZipArchiveEntry zipFileEntry = zipArchive.CreateEntry(fileToZip.Key);
//add the file contents
using Stream zipEntryStream = zipFileEntry.Open();
await responseStream.CopyToAsync(zipEntryStream);
}
}
zipArchive.Dispose();
}
zipMS.Seek(0, SeekOrigin.Begin);
var fileTxfr = new TransferUtility(s3client);
await fileTxfr.UploadAsync(zipMS, "dev-s3-zip-bucket", "test.zip");
}
I have a problem with get files to zip.
The web service is giving me the right files, for example www.XYP.com/GetFile?=1234 , when I open the Url, automaticly downloads the file, but after I zip this document its not correct files, which are destroyes
My code is here:
private void CreatedZipFile(Dictionary<int, string> listChecked)
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (KeyValuePair<int, string> kvp in listChecked)
{
ZipArchiveEntry demoFile = archive.CreateEntry(kvp.Key.ToString() + kvp.Value.ToString() + ".pdf");
string strDownLoad = System.Configuration.ConfigurationManager.AppSettings["GETFILESERVICES"] + kvp.Key.ToString();
WebService control = new WebService();
var clientnew = new System.Net.WebClient().DownloadData(strDownLoad);
using (var entryStream = demoFile.Open())
{
using (StreamWriter streamWriter = new StreamWriter(entryStream))
{
streamWriter.BaseStream.Write(clientnew, 0, clientnew.Length);
streamWriter.Close();
}
}
}
}
byte[] bytesInStream = memoryStream.ToArray();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=file.zip");
Response.Buffer = true;
Response.Clear();
Response.BinaryWrite(bytesInStream);
Response.Flush();
//MemoryStream.WriteTo(Response.OutputStream); //works too
Response.End();
}
}
Thanks for help or any advice,
I tried below code to first convert my bytes to compressed bytes and try to create a zip file, but file is not generated. Could someone please suggest!
byte[] result;
var X = 86251;
byte[] compressedBytes;
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
SourceStream.Seek(0, SeekOrigin.Begin);
result = new byte[X];
await SourceStream.ReadAsync(result, 0, X);
}
string fileName = "Export_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";
using (var outStream = new MemoryStream())
{
using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);
using (var entryStream = fileInArchive.Open())
using (var fileToCompressStream = new MemoryStream(result))
{
fileToCompressStream.CopyTo(entryStream);
}
}
compressedBytes = outStream.ToArray();
}
You're not creating an actual file anywhere. You're just writing to a memory stream. Change it to write to a file.
using (var outStream = new File.Create(fileName))
{
using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
var fileInArchive = archive.CreateEntry(filename, CompressionLevel.Optimal);
using (var entryStream = fileInArchive.Open())
using (var fileToCompressStream = new MemoryStream(result))
{
fileToCompressStream.CopyTo(entryStream);
}
}
}
I have read several blog posts and questions about this, but I can't get this working. It just downloads a corrupt ZIP archive that is <2KB. I feel like I'm missing something simple with streaming the PDF file to the Zip Archive?
using (var outStream = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
foreach (string Item in Items)
{
ReportParameter[] prms = new ReportParameter[1];
prms[0] = new ReportParameter("Item", Item, false);
rv.ServerReport.SetParameters(prms);
rv.ShowParameterPrompts = false;
rv.ServerReport.Refresh();
byte[] bytes = rv.ServerReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
string fileName = Item + ".pdf";
var fileInArchive = archive.CreateEntry(fileName);
using (var entryStream = fileInArchive.Open())
using (var fileToCompressStream = new MemoryStream(bytes))
{
fileToCompressStream.CopyTo(entryStream);
}
}
}
outStream.Position = 0;
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("content-disposition", "attachment; filename=PDFReports_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip");
Response.Write(outStream);
}
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 (i.e. /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))
{
…
}