C# provides a variety of classes that provide services to deal with compression and decompression of data (and files as well).Most of them provide you with methods to create ZIP archives from files,folders or streams.These classes are defined under the following namespace :
- System.IO.Compression
To use this namespace in your projects you’ll need to add a reference to “System.IO.Compression.dll” assembly.This namespace provides the following classes suited for compression,decompression and reading of data(and files as well).
- DeflateStream : Provides methods and properties for compressing and decompressing streams using the Deflate algorithm.
- GzipStream : Provides methods and properties used to compress and decompress streams.
- ZipArchive : Represents a package of compressed files in ZIP archive format.
- ZipArchiveEntry : Represents a compressed file within a ZIP archive.
- ZipFile : Provides static methods for creating,extracting and opening ZIP archives.
So those were the classes offered by .NET and thus C# for compression and decompression.As this tutorial is not going to be a long essay,so I’ll not discuss each class,MSDN already has enough documentation on the topic.So lets start by discussing the class ZipFile.This class,as its name suggests,provides basic services(static methods) to deal with ZIP archives i.e creation and extraction.To get started let’s try to compress some files and folders using this class.ZipFile has two methods to deal with compression and decompression,they are ,
- CreateFromDirectory : “Creates a zip archive that contains the files and directories from the specified directory.”As the documentation itself says this method allows you to create a Zip archive from the specified folder.It requires a path to a valid folder as first required argument,a destination archive name as second required argument.Other overloads provide a level of compression to be applied and a value specifying whether the base directory should be included or not.
- ExtractToDirectory : “Extracts all the files in the specified zip archive to a directory on the file system.”This method is almost an inverse of the first one,as first required argument it demands a path to a valid Zip archive and the second argument demands a path to put the extracted files.
CreateFromDirectory :
So let’s start by trying out the first method,to follow along create a new ConsoleApplication project in Visual Studio or the IDE of your choice,name it “Compression Test”.Here is the code to create a compressed archive from files(PS : The code below can be immediately compiled,just overwrite the code in your Program.cs file with this one) :
using
System; using System.IO; using System.IO.Compression;namespace Compression_Test
{
class Program{
static void Main(string[] args){
#region Input Path routine // The Input folder to archive. string inputPath = null; // The Output folder to put the resulting archive. string outputPath = null; // To check if the Input folder is valid one. bool sourceFolderIsValid = false; // Loop recursively until a valid folder path is entered. while (sourceFolderIsValid != true){
Console.WriteLine("Please enter path of a folder to archive..."); inputPath = Console.ReadLine(); if (inputPath.Contains("\""))// Strip out inverted commas from the path,if any,as they make the path invalid. inputPath = inputPath.Replace("\"", ""); if (!Directory.Exists(inputPath))// In each iteration,check if this time a valid path has been entered.{
Console.WriteLine("The source folder is invalid.Please try again"); Console.WriteLine(); sourceFolderIsValid = false;// Set this to false to keep the loop running.}
else// A valid path is found,break the loop.{
sourceFolderIsValid = true;// Set this to true to break the loop.}
}
#endregion#region Output Path routine // To check if the Output folder is valid one. bool outputFolderIsValid = false; while (outputFolderIsValid != true)// Loop recursively to check for a valid path.
{
Console.WriteLine("Please enter path to destination archive..."); outputPath = Console.ReadLine(); if (outputPath.Contains("\""))// Strip inverted commas from the path,if any,as they may make the path invalid. outputPath = outputPath.Replace("\"", ""); if (outputPath.Equals(inputPath))// Check if the destination path is not same as source path.{
Console.WriteLine("The destination folder cannot be same as source,please try with different one."); Console.WriteLine(); outputFolderIsValid = false;//Set this to false to keep the loop running.}
else// Hmm,this time the destination is not same as source,but is it valid ?{
if (!Directory.Exists(outputPath))// Check if the path is valid.{
Console.WriteLine("The destination folder is invalid.Please try again"); Console.WriteLine(); outputFolderIsValid = false;//Set this to false to keep the loop running.}
else{
outputFolderIsValid = true;// Set this to true to break the loop.}
}
}
#endregion#region Compression Routine Console.WriteLine("Please wait...Compressing files"); Console.WriteLine(); try
{
// Create a temporary path to check for files whose names might conflict with this archive’s name. string tempOutputPath = string.Format("{0}\\Compressed Archive.zip", outputPath); if (!File.Exists(tempOutputPath))// Check if the path already exists.{
ZipFile.CreateFromDirectory(inputPath, tempOutputPath);//No,it doesn’t,we can use this one.}
else// Damn,the path already exists,we need to create a similar version ourselves.{
for (int counter = 1; ; counter++)// We're going to use the numbering technique as Explorer uses.{
tempOutputPath = string.Format("{0}\\Compressed Archive {1}.zip", outputPath, counter);// Create a path with current value of counter. if (!File.Exists(tempOutputPath))// Check if the new path exists.{
ZipFile.CreateFromDirectory(inputPath, tempOutputPath);//No,it doesn’t,we’ll use this one. break;// Break the loop.}
}
}
Console.WriteLine("The archive has been created successfully.Press Enter to exit.");// Greet the user and say bye. Console.ReadKey();}
catch (Exception exception){
Console.WriteLine(exception.Message); Console.WriteLine(); Console.WriteLine("Press enter to exit."); Console.ReadLine();}
#endregion}
}
}
Go on,build and run the project,enter a folder path that has some files in it,press Enter,then enter a target folder(use Desktop=>%SystemRoot/Users/UserName/Desktop for now),press Enter and you’ll see a compressed archive on your Desktop.Here is the project which I’ve compressed using the application we created just now.Missed out anything,please point it out.In the next tutorial we’ll be discussing Decompression.
No comments :
Post a Comment