How to Zip a File in C#, Using No 3Rd-Party APIs

How do I ZIP a file in C#, using no 3rd-party APIs?

Are you using .NET 3.5? You could use the ZipPackage class and related classes. Its more than just zipping up a file list because it wants a MIME type for each file you add. It might do what you want.

I'm currently using these classes for a similar problem to archive several related files into a single file for download. We use a file extension to associate the download file with our desktop app. One small problem we ran into was that its not possible to just use a third-party tool like 7-zip to create the zip files because the client side code can't open it -- ZipPackage adds a hidden file describing the content type of each component file and cannot open a zip file if that content type file is missing.

Zipping files in ASP.NET without using free third-party solutions

There is always System.IO.Compression which features a class called GZipStream.
The ability to write real *.zip files will only be added in .NET 4.5 (see System.IO.Compression in 4.5).

So for now you can either try to write your own implementation (not recommended) or use a third-party component. Depending on the license of the component, you might be able to copy its code into your project (making patches to the component a bit cumbersome). The GPL for instance only requires you to release your source code when you distribute your derivative work. But in the case of a web application where no code or binary is actually given away, there are no consequences to using a GPL-ed library.

Programmatically zip files from SharePoint document library (no 3rd party tools)

It looks like you're creating a brand new zip file instead of updating an existing one (let me know if my assumption is wrong). If you want to create a zip archive in memory instead of creating the zip file on disk then you can use the ZipArchive class.

using (MemoryStream stream = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create))
{
archive.CreateEntryFromFile(fileToPutInZip, fileNameInZip);
}

// To get the zip bytes (i.e. to return in HTTP response maybe):
byte[] bytes = stream.ToArray();

// TODO: Do something with zip bytes
}

Zip a Folder Created in C#

To zip a folder, the .Net 4.5 framework contains ZipFile.CreateFromDirectory:

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";

ZipFile.CreateFromDirectory(startPath, zipPath);

How to save Zip file on local machine which is coming from HttpClient using SaveFileDialog in Windows application using C#?

The problem lies in the method, ToRetrieve.

With streamToReadFrom being in a using statement, the Dispose method will be called.

Since result contains the reference, you are returning a closed stream.



Related Topics



Leave a reply



Submit