C#文件压缩成.Zip

时间:2019-11-11
本文章向大家介绍C#文件压缩成.Zip,主要包括C#文件压缩成.Zip使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用的三方类库ICSharpCode.SharpZipLib.dll

方法如下:

 /// <summary>
        /// 压缩文件为zip格式
        /// </summary>
        /// <param name="filepath">文件地址</param>
        /// <param name="targetPath">目标路径</param>
        static bool CompressFiles(string filePath, string targetPath)
        {
            try
            {
                using (ZipOutputStream zipstream = new ZipOutputStream(File.Create(targetPath)))
                {
                    zipstream.SetLevel(9); // 压缩级别 0-9
                    byte[] buffer = new byte[4096]; //缓冲区大小
                    ZipEntry entry = new ZipEntry(Path.GetFileName(filePath));
                    entry.DateTime = DateTime.Now;
                    zipstream.PutNextEntry(entry);
                    using (FileStream fs = File.OpenRead(filePath))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            zipstream.Write(buffer, 0, sourceBytes);
                        }
                        while (sourceBytes > 0);
                    }
                    zipstream.Finish();
                    zipstream.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {                
                return false;
            }
        }

原文地址:https://www.cnblogs.com/cdjbolg/p/11835835.html