ZipArchive Create Entry using Zip File to memory stream - c#

I am using Zip Archive to create a zip folder with various files and subfolders and returning it as a memory stream like so.
public MemoryStream CreateAZipFolder(){
var stMarged = new System.IO.MemoryStream();
stMarged.Position = 0;
using (MemoryStream zipStream = new MemoryStream())
{
using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
string[] fileEntries = Directory.GetFiles(#"C:\Applications\folder");
foreach (var fileName in fileEntries)
{
zip.CreateEntryFromFile(fileName, "Applications/folder/" + Path.GetFileName(fileName),
CompressionLevel.Optimal);
}
ZipArchiveEntry batchEntry = zip.CreateEntry("mybatchFile.bat");
using (StreamWriter writer = new StreamWriter(batchEntry.Open()))
{
writer.Write(batchFile);
}
//Add the xml file to zip folder
ZipArchiveEntry entry = zip.CreateEntry("nCounterConfig.xml");
using (StreamWriter writer = new StreamWriter(entry.Open()))
{
writer.Write(xdoc.OuterXml);
}
}
zipStream.Position = 0;
return zipStream;
I would like to add a directory with sub directories and files to this memory stream. I found that ZipFile has a method "CreateFromDirectory" which would be ideal except it requires a paramater for an output folder the method also does not have a return type. How can i zip all the files and subfolders in a directory and add them to my memory stream using ZipFile?
something like this
zip.CreateEntry(ZipFile.CreateFromDirectory(
#"C:\morefilestozip\", "",
CompressionLevel.Fastest, true));

Related

Save compressed files in file system

I want to save multiple files in one Zip file on my disc. This Zip is created but his type is "Compressed (zipped) Folder" and is impossible to open. Error: "Windows cannot open the folder. The Compressed (zipped) Folder 'path' is invalid. Can I make it normal .Zip file somehow?
int i = 0;
await using var ms = new MemoryStream();
{
using var archive = new ZipArchive(ms, ZipArchiveMode.Create, true);
{
foreach (var s in stepwiseData)
{
//streamWriter.Write(s);
var entry = archive.CreateEntry($"Name {i.ToString()}");
i++;
using (BinaryWriter writer = new BinaryWriter(entry.Open()))
{
writer.Write(s.ToArray());
}
}
var folder = #"C:\Temp\test\";
var fileName = "TestName.zip";
var fullPath = folder + fileName;
var bytes = ms.ToArray();
File.WriteAllBytes(fullPath, bytes);
}
}

Zip S3 files using C#

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");
}

Get Filestream from ZipArchive

I have a function that requires a Filestream as input.
I want to hand several Files to that function which I get from uploaded zip-Files.
Is it possible to create the Filestream without extracting the file to a temporary folder?
I imagin something like this:
string path = #"C:\somepathtomyzip";
string filepath = "nameofimagefile"
using (ZipArchive archive = ZipFile.OpenRead(path))
{
ZipArchiveEntry entry = archive.GetEntry(file_path);
//generate Filestream from entry
myFunction(filestreamIneed);
}
You can use ZipArchiveEntry.Open() and copy the output from the returned Stream instance to a FileStream instance:
using (ZipArchive archive = ZipFile.OpenRead(path))
{
ZipArchiveEntry entry = archive.GetEntry(file_path);
var memoryStream = return entry.Open();
using (var fileStream = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite))
{
memoryStream.CopyTo(fileStream); // fileStream is not populated
}
}

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 (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))
{
…
}

windows store adding files in zip archieve dynamically

I have got a code from this link:
http://www.codeproject.com/Tips/515704/Archive-Multiple-Files-In-Zip-Extract-Zip-Archive
that compresses and extracts a file in zip format.
However the compressing part in the code just creates an empty zipfile, so how can i add files programmatically in this zip archieve?
i have checked the doc for the ziparchieve class and it has a method for .net called CreateEntryFromFile(String, String) , however this method doesn't apply for .net windows store version.
this is the code we are concerned with:
private async void ZipClick(object sender, RoutedEventArgs e)
{
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("Zip Files (*.zip)", new List<string> { ".zip" });
picker.SuggestedStartLocation = PickerLocationId.Desktop;
picker.SuggestedFileName = "1";
zipFile = await picker.PickSaveFileAsync();
using (var zipStream = await zipFile.OpenStreamForWriteAsync())
{
using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
foreach (var file in storeFile)
{
ZipArchiveEntry entry = zip.CreateEntry(file.Name);
using (Stream ZipFile = entry.Open())
{
byte[] data = await GetByteFromFile(file);
ZipFile.Write(data, 0, data.Length);
}
}
}
}
}
I misunderstood the sample code, it actually can archive the the files you pass it for the first time, but i'm not sure if the same method can be used to add to add other files in the same zip file later.
public async void zipit(StorageFile zipFile, StorageFile file)
{
using (var zipToOpen = await zipFile.OpenStreamForWriteAsync())
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.CreateEntry(file.Name);
using (Stream writer = readmeEntry.Open())
{
//writer.WriteLine("Information about this package.");
//writer.WriteLine("========================");
byte[] data = await GetByteFromFile(file);
writer.Write(data, 0, data.Length);
}
}
}
}
where "zipFile" is the file you have chose to archive in (destination ) and "file" is the original non zipped file.

Categories

Resources