当前位置: 移动技术网 > IT编程>开发语言>.net > 基于.NET 4.5 压缩的使用

基于.NET 4.5 压缩的使用

2017年12月12日  | 移动技术网IT编程  | 我要评论
在.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);
        }

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网