I have seen many tutorials on how to compress a single file in c#. But I need to be able to create a normal *.zip file out of more than just one file. Is there anything in .NET that can do this? What would you suggest (baring in mind I'm under strict rules and cannot use other libraries)
Thank you
This question is related to
c#
.net
winforms
compression
zip
Just an update on this for anyone else who stumbles across this question.
Starting in .NET 4.5 you are able to compress a directory using System.IO.Compression
into a zip file. You have to add System.IO.Compression.FileSystem
as a reference as it is not referenced by default. Then you can write:
System.IO.Compression.ZipFile.CreateFromDirectory(dirPath, zipFile);
The only potential problem is that this assembly is not available for Windows Store Apps.
.NET has a built functionality for compressing files in the System.IO.Compression namespace. Using this you do not have to take an extra library as a dependency. This functionality is available from .NET 2.0.
Here is the way to do the compressing from the MSDN page I linked:
public static void Compress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Prevent compressing hidden and already compressed files.
if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
!= FileAttributes.Hidden & fi.Extension != ".gz")
{
// Create the compressed file.
using (FileStream outFile = File.Create(fi.FullName + ".gz"))
{
using (GZipStream Compress = new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into the compression stream.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
Compress.Write(buffer, 0, numRead);
}
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
Here's some code I wrote after using the above posts. Thanks for all your help.
This code accepts a list of file paths and creates a zip file out of them.
public class Zip
{
private string _filePath;
public string FilePath { get { return _filePath; } }
/// <summary>
/// Zips a set of files
/// </summary>
/// <param name="filesToZip">A list of filepaths</param>
/// <param name="sZipFileName">The file name of the new zip (do not include the file extension, nor the full path - just the name)</param>
/// <param name="deleteExistingZip">Whether you want to delete the existing zip file</param>
/// <remarks>
/// Limitation - all files must be in the same location.
/// Limitation - must have read/write/edit access to folder where first file is located.
/// Will throw exception if the zip file already exists and you do not specify deleteExistingZip
/// </remarks>
public Zip(List<string> filesToZip, string sZipFileName, bool deleteExistingZip = true)
{
if (filesToZip.Count > 0)
{
if (File.Exists(filesToZip[0]))
{
// Get the first file in the list so we can get the root directory
string strRootDirectory = Path.GetDirectoryName(filesToZip[0]);
// Set up a temporary directory to save the files to (that we will eventually zip up)
DirectoryInfo dirTemp = Directory.CreateDirectory(strRootDirectory + "/" + DateTime.Now.ToString("yyyyMMddhhmmss"));
// Copy all files to the temporary directory
foreach (string strFilePath in filesToZip)
{
if (!File.Exists(strFilePath))
{
throw new Exception(string.Format("File {0} does not exist", strFilePath));
}
string strDestinationFilePath = Path.Combine(dirTemp.FullName, Path.GetFileName(strFilePath));
File.Copy(strFilePath, strDestinationFilePath);
}
// Create the zip file using the temporary directory
if (!sZipFileName.EndsWith(".zip")) { sZipFileName += ".zip"; }
string strZipPath = Path.Combine(strRootDirectory, sZipFileName);
if (deleteExistingZip == true && File.Exists(strZipPath)) { File.Delete(strZipPath); }
ZipFile.CreateFromDirectory(dirTemp.FullName, strZipPath, CompressionLevel.Fastest, false);
// Delete the temporary directory
dirTemp.Delete(true);
_filePath = strZipPath;
}
else
{
throw new Exception(string.Format("File {0} does not exist", filesToZip[0]));
}
}
else
{
throw new Exception("You must specify at least one file to zip.");
}
}
}
This can be done by adding a reference to System.IO.Compression and System.IO.Compression.Filesystem.
A sample createZipFile() method may look as following:
public static void createZipFile(string inputfile, string outputfile, CompressionLevel compressionlevel)
{
try
{
using (ZipArchive za = ZipFile.Open(outputfile, ZipArchiveMode.Update))
{
//using the same file name as entry name
za.CreateEntryFromFile(inputfile, inputfile);
}
}
catch (ArgumentException)
{
Console.WriteLine("Invalid input/output file.");
Environment.Exit(-1);
}
}
where
You should look into Zip Packages
They are a more structured version of normal ZIP archives, requiring some meta stuff in the root. So other ZIP tools can open a package, but the Sysytem.IO.Packaging API can not open all ZIP files.
You can try SharpZipLib for that. Is is open source, platform independent pure c# code.
You can now use the ZipArchive class (System.IO.Compression.ZipArchive), available from .NET 4.5
You have to add System.IO.Compression
as a reference.
Example: Generating a zip of PDF files
using (var fileStream = new FileStream(@"C:\temp\temp.zip", FileMode.CreateNew))
{
using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
{
foreach (var creditNumber in creditNumbers)
{
var pdfBytes = GeneratePdf(creditNumber);
var fileName = "credit_" + creditNumber + ".pdf";
var zipArchiveEntry = archive.CreateEntry(fileName, CompressionLevel.Fastest);
using (var zipStream = zipArchiveEntry.Open())
zipStream.Write(pdfBytes, 0, pdfBytes.Length);
}
}
}
}
This can be done with just one line of code using just Dot Net. Below is sample code copied from MSDN
Step 1: Add a reference to System.IO.Compression.FileSystem
Step 2: Follow the code below
static void Main(string[] args)
{
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
Here are a few resources you might consider: Creating Zip archives in .NET (without an external library like SharpZipLib)
Zip Your Streams with System.IO.Packaging
My recommendation and preference would be to use system.io.packacking. This keeps your dependencies down (just the framework). Jgalloway’s post (the first reference) provides a good example of adding two files to a zip file. Yes, it is more verbose, but you can easily create a façade (to a degree his AddFileToZip does that).
HTH
My 2 cents:
using (ZipArchive archive = ZipFile.Open(zFile, ZipArchiveMode.Create))
{
foreach (var fPath in filePaths)
{
archive.CreateEntryFromFile(fPath,Path.GetFileName(fPath));
}
}
So Zip files could be created directly from files/dirs.
Source: Stackoverflow.com