Use of.ES0en 4.5 compression

  • 2020-06-03 06:13:13
  • OfStack

New compressed namespaces and methods added in.NET 4.5. The ICSharpCode.SharpZipLib.dll class library can be discarded. Comparable in performance. But it can greatly simplify your code. If you start using.NET FrameWork4.5 compression might as well try your own compression method.

Traditional ICSharpCode.SharpZipLib.dll code.


static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            string path = @"E:\";        
            Compress(Directory.GetFiles(path), @"F:\4.0.zip");
            watch.Stop();
            Console.WriteLine(" Elapsed time :{0}", watch.ElapsedMilliseconds);
            FileInfo f = new FileInfo(@"F:\4.0.zip");
            Console.WriteLine(" The file size {0}", f.Length);
        }
        static void Compress(string[] filePaths, string zipFilePath)
        {
            byte[] _buffer = new byte[4096];
            if (!Directory.Exists(zipFilePath))
                Directory.CreateDirectory(Path.GetDirectoryName(zipFilePath));
            using (ZipOutputStream zip = new ZipOutputStream(File.Create(zipFilePath)))
            {
                foreach (var item in filePaths)
                {
                    if (!File.Exists(item))
                    {
                        Console.WriteLine("the file {0} not exist!", item);
                    }
                    else
                    {
                        ZipEntry entry = new ZipEntry(Path.GetFileName(item));
                        entry.DateTime = DateTime.Now;
                        zip.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(item))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(_buffer, 0, _buffer.Length);
                                zip.Write(_buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                }
                zip.Finish();
                zip.Close();
            }
        }

Use the compression built into.NET FrameWork 4.5.

static void Main(string[] args)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            string path = @"E:\";
            Compress(path, @"F:\4.5.zip");
            watch.Stop();
            Console.WriteLine(" Elapsed time :{0}", watch.ElapsedMilliseconds);
            FileInfo f = new FileInfo(@"F:\4.5.zip");
            Console.WriteLine(" The file size {0}", f.Length);
        }
        static void Compress(string filePath, string zipFilePath)
        {
            ZipFile.CreateFromDirectory(filePath, zipFilePath, CompressionLevel.Fastest, false);
        }

How is the code a lot cleaner?


Related articles: