温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

.NET4.5如何实现压缩

发布时间:2021-10-14 13:59:31 来源:亿速云 阅读:110 作者:小新 栏目:开发技术

这篇文章主要介绍.NET4.5如何实现压缩,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

在.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);
        }

以上是“.NET4.5如何实现压缩”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI