欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于.NET 4.5 压缩的使用

程序员文章站 2024-03-02 09:06:13
在.net 4.5中新加入的压缩的命名空间和方法。可以抛弃icsharpcode.sharpziplib.dll 这个类库了。性能上不相上下。但是能够大大简化你的代码。如果...

在.net 4.5中新加入的压缩的命名空间和方法。可以抛弃icsharpcode.sharpziplib.dll 这个类库了。性能上不相上下。但是能够大大简化你的代码。如果开始使用.net framework4.5 做压缩不妨试试自带的压缩方法.

传统使用icsharpcode.sharpziplib.dll 所写的代码。

复制代码 代码如下:

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("消耗时间:{0}", watch.elapsedmilliseconds);
            fileinfo f = new fileinfo(@"f:\4.0.zip");
            console.writeline("文件大小{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();
            }
        }


使用.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("消耗时间:{0}", watch.elapsedmilliseconds);
            fileinfo f = new fileinfo(@"f:\4.5.zip");
            console.writeline("文件大小{0}", f.length);
        }
        static void compress(string filepath, string zipfilepath)
        {
            zipfile.createfromdirectory(filepath, zipfilepath, compressionlevel.fastest, false);
        }

怎么样代码是不是简洁了很多呢?