C# Serialization Guide Part 8 – Zip files

27 בMay 2014

אין תגובות

Writing to an zip file is very easy , this is actually required some algorithm to build the internal file hierarchy, the Zip/Rar file is built from what we called Entries , and those entries are kept like a stack one above each other so our job is to build this stack , also if required we need to extract

.the files from it

.I am definitely not ganna writing the full demo, only a starter using the new ZipFile API

;ZipFiles usage could be one of two major tasks (or both)

.1

.compress to Zip files is a solution for a large scale of data, so we need to compress it

.2

.A few Docs, or files which is together complex a custom file format

In .NET 4.5 we have got a new API which I found really friendly, I used to write a long

.implementation but it is very easy now

The required DLL is : System.IO.Compression.FileSystem.dll , this is an extension to the System.IO.Compression, and just hold it inside with very important edition, the ZipFile static

.class

.This class provide simple way to create, read and write to and from zip files

:To test it lets create directory with files

string directoryPath = "C://ZipTest1";


if(!Directory.Exists(directoryPath))

{

    Directory.CreateDirectory( directoryPath);

}

,This is simple as you read it

:Now, lets fill it with some sheets, (not shits.. even if we mean it)

for (int i = 0; i < 10; i++)

            {

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(directoryPath + "/"+i+".txt"))

                {

                    for (int x = 0; x < 100; x++)

                    {

                          file.WriteLine(DateTime.Now.ToFileTime());

                    }

                }

            }

,The result is a Folder with some files and the size is about 20 kb

.Of course in this stage we can serialize inside everything else, like if we use the xmlserializer

.Anyway This is the time for the ZipFile Class

string zipPath = directoryPath + "rar";


            System.IO.Compression.ZipFile.CreateFromDirectory(directoryPath, zipPath, CompressionLevel.Fastest, true, Encoding.ASCII);

!That simple line will create an compressed folder of about 2 kb

?What about to extract those files

:we just need to provide the source and the target, than run this code

string zipPathExtractor = directoryPath + "results";


            ZipFile.ExtractToDirectory(zipPath, zipPathExtractor, Encoding.ASCII);


הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *