zip files in server - c#

How can I zip (In the server) multiple files to one archive?

Following code uses our Rebex ZIP and shows how to add files into the ZIP archive without using any temp file. The ZIP is then sent to the web browser.
// prepare MemoryStream to create ZIP archive within
using (MemoryStream ms = new MemoryStream())
{
// create new ZIP archive within prepared MemoryStream
using (ZipArchive zip = new ZipArchive(ms))
{
// add some files to ZIP archive
zip.Add(#"c:\temp\testfile.txt");
zip.Add(#"c:\temp\innerfile.txt", #"\subfolder");
// clear response stream and set the response header and content type
Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=sample.zip");
// write content of the MemoryStream (created ZIP archive)
// to the response stream
ms.WriteTo(Response.OutputStream);
}
}
// close the current HTTP response and stop executing this page
HttpContext.Current.ApplicationInstance.CompleteRequest();
For more info see ZIP tutorial.
Alternative solution:
SharpZipLib and DotNetZip a widely used free alternatives.

Take a look at SharpZipLib or DotNetZip

Codeplex has Dot Net Zip http://dotnetzip.codeplex.com/
You can also try System.IO.Compression

Related

How to zip audio files before downloading in wp8 same as Google Drive

I am downloading several audio files one by one using BackgroundTransferRequest and the some of the downloads could be upto 70 MB. I am thinking of zipping these audio files before downloading (the same when downloading multiple files from Google drive).
Just to make it clear, I don't want to store zip files in Isolated storage, I just need to compress audio files in the fly and then download the zipped version using BackgroundTransferRequest and finally decompress it.
Is it possible to Zip audio files before downloading in wp8?
Do I need third party tool for it or .Net provide compression / decompression classes for it?
Thanks!
You can't zip something you haven't downloaded yet, unless you're downloading it from your own web service?
If you are, .NET provides the GZipCompression classes to handle ZIP files.
I use Ionic.Zip library for making zip-files:
here is an example to zip a file:
string audiofile = AppDomain.CurrentDomain.BaseDirectory;
using (Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile())
{
using (MemoryStream tempstream = new MemoryStream())
{
string fileName = "song.mp3";
string filepath = audiofile + "song.mp3";
byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
zipFile.AddEntry(fileName, fileBytes);
}
}
Guid g = new Guid();
g = Guid.NewGuid();
string path = audiofile + "Temp\\" + g.ToString() + ".Zip";
zipFile.Save(path);
// RETURN FILE USING YOUR BACKGROUNDTRANSFERREQUEST HERE with the path-variable
}

Decompressing a Zip file from a string

I'm fetching an object from couchbase where one of the fields has a file. The file is zipped and then encoded in base64.
How would I be able to take this string and decompress it back to the original file?
Then, if I'm using ASP.MVC 4 - How would I send it back to the browser as a downloadable file?
The original file is being created on a Linux system and decoded on a Windows system (C#).
You should use Convert.FromBase64String to get the bytes, then decompress, and then use Controller.File to have the client download the file. To decompress, you need to open the zip file using some sort of ZIP library. .NET 4.5's built-in ZipArchive class should work. Or you could use another library, both SharpZipLib and DotNetZip support reading from streams.
public ActionResult MyAction()
{
string base64String = // get from Linux system
byte[] zipBytes = Convert.FromBase64String(base64String);
using (var zipStream = new MemoryStream(zipBytes))
using (var zipArchive = new ZipArchive(zipStream))
{
var entry = zipArchive.Entries.Single();
string mimeType = MimeMapping.GetMimeMapping(entry.Name);
using (var decompressedStream = entry.Open())
return File(decompressedStream, mimeType);
}
}
You'll also need the MIME type of the file, you can use MimeMapping.GetMimeMapping to help you get that for most common types.
I've used SharpZipLib successfully for this type of task in the past.
For an example that's very close to what you need to do have a look here.
Basically, the steps should be something like this:
you get the compressed input as a string from the database
create a MemoryStream and write the string to it
seek back to the beginning of the memory stream
use the MemoryStream as an input to the SharpZipLib ZipFile class
follow the example provided above to unpack the contents of the ZipFile
Update
If the string contains only the zipped contents of the file (not a full Zip archive) then you can simply use the GZipStream class in .NET to unzip the contents. You can find a sample here. But the initial steps are the same as above (get string from db, write to memory stream, feed memory stream as input to the GZipStream to decompress).

DotNetZip Library read from one zip into another

Using the DotNetZip Library (http://dotnetzip.codeplex.com/) is there a way to move files from one zip file into another without extracting that file to disk first? Maybe extract to a stream, then update into the other zip from that same stream?
The zip files are password protected and the data in these zip files are meant to stay that way due to their licenses. If I simply extract to disk first then update the other zip there is a chance where those files can be intercepted by the user.
Yes, you should be able to do something like;
var ms = new MemoryStream();
using (ZipFile zip = ZipFile.Read(sourceZipFile))
{
zip.Extract("NameOfEntryInArchive.doc", ms);
}
ms.Seek(0);
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("NameOfEntryInArchive.doc", ms);
zip.Save(zipToCreate);
}
(see it as pseudocode since I didn't have a chance to compile)
Naturally you'll have to add your decryption/encryption to that, but those calls are equally straight forward.

How to get type and number of .zip contents

How can i get the content names of a zipped folder in C# i.e. name of files and folders inside the compressed folder?
I want to decompress the zip by using GZipStream only.
thanks,
kapil
You can't do this using GZipStream only. You will need an implementation of the ZIP standard such as #ziplib. Quote from MSDN:
Compressed GZipStream objects written
to a file with an extension of .gz can
be decompressed using many common
compression tools; however, this class
does not inherently provide
functionality for adding files to or
extracting files from .zip archives.
Example with #ziplib:
using (var stream = File.OpenRead("test.zip"))
using (var zipStream = new ZipInputStream(stream))
{
ZipEntry entry;
while ((entry = zipStream.GetNextEntry()) != null)
{
// entry.IsDirectory, entry.IsFile, ...
Console.WriteLine(entry.Name);
}
}

Unzipping a .gz file using C#

I have a tarred gunzip file called ZippedXmls.tar.gz which has 2 xmls inside it.
I need to programmatically unzip this file and the output should be 2 xmls copied in a folder.
How do I achieve this using C#?
I've used .Net's built-in GZipStream for gzipping byte streams and it works just fine. I suspect that your files are tarred first, before being gzipped.
You've asked for code, so here's a sample, assuming you have a single file that is zipped:
FileStream stream = new FileStream("output.xml", FileMode.Create); // this is the output
GZipStream uncompressed = new GZipStream(stream, CompressionMode.Decompress);
uncompressed.Write(bytes,0,bytes.Length); // write all compressed bytes
uncompressed.Flush();
uncompressed.Close();
stream.Dispose();
Edit:
You've changed your question so that the file is a tar.gz file - technically my answer is not applicable to your situation, but I'll leave it here for folks who want to handle .gz files.
sharpziplib should be able to do this
I know this question is ancient, but search engines redirect here for how to extract gzip in C#, so I thought I'd provide a slightly more recent example:
using (var inputFileStream = new FileStream("c:\\myfile.xml.gz", FileMode.Open))
using (var gzipStream = new GZipStream(inputFileStream, CompressionMode.Decompress))
using (var outputFileStream = new FileStream("c:\\myfile.xml", FileMode.Create))
{
await gzipStream.CopyToAsync(outputFileStream);
}
For what should be the simpler question of how to untar see: Decompress tar files using C#

Categories