Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress a single file using C#

Tags:

c#

.net

zip

zipfile

People also ask

How do I compress a single file?

To zip (compress) a file or folder Locate the file or folder that you want to zip. Press and hold (or right-click) the file or folder, select (or point to) Send to, and then select Compressed (zipped) folder. A new zipped folder with the same name is created in the same location.

How do I condense a file size?

Remove unnecessary images, formatting and macros. Save the file as a recent Word version. Reduce the file size of the images before they are added to the document. If it is still too large, save the file as a PDF.


Use the CreateEntryFromFile off a an archive and use a file or memory stream:

Using a filestream if you are fine creating the zip file and then adding to it:

using (FileStream fs = new FileStream(@"C:\Temp\output.zip",FileMode.Create))
using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Create))
{
    arch.CreateEntryFromFile(@"C:\Temp\data.xml", "data.xml");
}

Or if you need to do everything in memory and write the file once it is done, use a memory stream:

using (MemoryStream ms = new MemoryStream())
using (ZipArchive arch = new ZipArchive(ms, ZipArchiveMode.Create))
{
    arch.CreateEntryFromFile(@"C:\Temp\data.xml", "data.xml");
}

Then you can write the MemoryStream to a file.

using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write)) {
   byte[] bytes = new byte[ms.Length];
   ms.Read(bytes, 0, (int)ms.Length);
   file.Write(bytes, 0, bytes.Length);
   ms.Close();
}

Using file (or any) stream:

using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
{
    var entry = zip.CreateEntry("file.txt");
    entry.LastWriteTime = DateTimeOffset.Now;

    using (var stream= File.OpenRead(@"c:\path\to\file.txt"))
    using (var entryStream = entry.Open())
        stream.CopyTo(entryStream);
}

or briefer:

// reference System.IO.Compression
using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
    zip.CreateEntryFromFile("file.txt", "file.txt");

make sure you add references to System.IO.Compression

Update

Also, check out the new dotnet API documentation for ZipFile and ZipArchive too. There are a few examples there. There is also a warning about referencing System.IO.Compression.FileSystem to use ZipFile.

To use the ZipFile class, you must reference the System.IO.Compression.FileSystem assembly in your project.


The simplest way to get this working is to use a temporary folder.

FOR ZIPPING:

  1. Create a temp folder
  2. Move file to folder
  3. Zip folder
  4. Delete folder

FOR UNZIPPING:

  1. Unzip archive
  2. Move file from temp folder to your location
  3. Delete temp folder